Hello, Laravel developers! In this article, I'll show you how to easily import and export CSV and Excel files in Laravel 11. We'll walk through the steps to import data from a CSV or Excel file and also how to export data back into these formats. I'll be using the maatwebsite/excel package to handle these tasks.
In this example, I'll create a simple form where users can upload a CSV file to add multiple users to the database. Then, I'll set up an export route that allows you to download all users from the database as an Excel file.
You can be exported with .csv, .xls, and .xlsx extensions. How to import CSV Excel files in laravel 11 using maatwebsite/excel.
In this step, we'll install laravel 11 using the following command.
composer create-project laravel/laravel laravel-11-example
Then, we'll install maatwebsite/excel composer package using the following command.
composer require maatwebsite/excel
Then, we'll create some dummy records using the tinker command.
php artisan tinker
User::factory()->count(50)->create()
Now, create a new Import class using the following command. For example, let's name it UsersImport
.
php artisan make:import UsersImport --model=User
app/Imports/UsersImport.php
<?php
namespace App\Imports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Hash;
class UsersImport implements ToModel, WithHeadingRow, WithValidation
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row['name'],
'email' => $row['email'],
'password' => Hash::make($row['password']),
]);
}
/**
* Write code on Method
*
* @return response()
*/
public function rules(): array
{
return [
'name' => 'required',
'password' => 'required|min:6',
'email' => 'required|email|unique:users'
];
}
}
File Example:
name | password | |
---|---|---|
abc | [email protected] | 123456 |
After that, we'll create a new Export class using the following command. For example, let's name it UsersExport
.
php artisan make:export UsersExport --model=User
app/Exports/UsersExport.php
<?php
namespace App\Exports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class UsersExport implements FromCollection, WithHeadings
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return User::select("id", "name", "email")->get();
}
/**
* Write code on Method
*
* @return response()
*/
public function headings(): array
{
return ["ID", "Name", "Email"];
}
}
In this step, I will create a UserController
with index()
, export()
, and import()
methods. So, run the following command to create a controller.
php artisan make:controller UserController
app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\UsersExport;
use App\Imports\UsersImport;
use App\Models\User;
class UserController extends Controller
{
/**
* @return \Illuminate\Support\Collection
*/
public function index()
{
$users = User::get();
return view('users', compact('users'));
}
/**
* @return \Illuminate\Support\Collection
*/
public function export()
{
return Excel::download(new UsersExport, 'users.xlsx');
}
/**
* @return \Illuminate\Support\Collection
*/
public function import(Request $request)
{
$request->validate([
'file' => 'required|max:2048',
]);
Excel::import(new UsersImport, $request->file('file'));
return back()->with('success', 'Users imported successfully.');
}
}
Now, we'll create routes into the web.php file.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
Route::get('users', [UserController::class, 'index']);
Route::get('users/export', [UserController::class, 'export'])->name('users.export');
Route::post('users/import', [UserController::class, 'import'])->name('users.import');
In this step, we'll create users.blade.php file. and add the HTML layout for importing and exporting CSV and Excel files in laravel 11.
resources/views/users.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 11 Import Export CSV and Excel File - Websolutionstuff</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
</head>
<body>
<div class="container">
<div class="card mt-5">
<h3 class="card-header p-3"><i class="fa fa-star"></i> Laravel 11 Import Export CSV and Excel File - Websolutionstuff</h3>
<div class="card-body">
@session('success')
<div class="alert alert-success" role="alert">
{{ $value }}
</div>
@endsession
@if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('users.import') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file" class="form-control">
<br>
<button class="btn btn-success"><i class="fa fa-file"></i> Import User Data</button>
</form>
<table class="table table-bordered mt-3">
<tr>
<th colspan="3">
List Of Users
<a class="btn btn-warning float-end" href="{{ route('users.export') }}"><i class="fa fa-download"></i> Export User Data</a>
</th>
</tr>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
@foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
</tr>
@endforeach
</table>
</div>
</div>
</div>
</body>
</html>
Now, run the laravel 11 application using the following command.
php artisan serve
You might also like:
Hello developers! In this article, we'll see how to create apexcharts bar chart in laravel 11. ApexCharts is a...
Apr-17-2024
In this example we will see laravel 8 datatables filter with dropdown, Here we will add datatables custom...
Jun-16-2021
In this article, we will see Queen Elizabeth II portrait using CSS. Elizabeth II was Queen of the United Kingd...
Sep-11-2022
If you're a developer, you're likely to have frustration with "index.php" cluttering up your website...
Jan-13-2023