In this tutorial, you will learn how to import and export CSV and Excel files in Laravel 12 using the Laravel Excel package. Importing and exporting files is a common requirement in many applications, especially when dealing with large datasets or migrating data between different systems.
By the end of this tutorial, you will be able to:
We will use the Laravel Excel package to handle the import and export functionality easily.
Let's get started:
Run the following command in your terminal to install the Laravel Excel package:
composer require maatwebsite/excel
Generate the import and export classes using Artisan command:
php artisan make:import UsersImport --model=User
php artisan make:export UsersExport --model=User
This will create two files in:
Modify the UsersImport.php file
app/Imports/UsersImport.php
<?php
namespace App\Imports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
class UsersImport implements ToModel
{
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => bcrypt($row[2]),
]);
}
}
Modify the UsersExport.php file:
app/Exports/UsersExport.php
<?php
namespace App\Exports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class UsersExport implements FromCollection
{
public function collection()
{
return User::all();
}
}
Now, create a new controller for handling the import and export logic:
php artisan make:controller UserController
Modify the UserController.php file:
app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Imports\UsersImport;
use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
class UserController extends Controller
{
public function import(Request $request)
{
Excel::import(new UsersImport, $request->file('file'));
return redirect()->back()->with('success', 'Users Imported Successfully');
}
public function export()
{
return Excel::download(new UsersExport, 'users.xlsx');
}
}
Open your web.php file and add the following routes:
routes/web.php
use App\Http\Controllers\UserController;
Route::get('/export', [UserController::class, 'export']);
Route::post('/import', [UserController::class, 'import']);
Create a simple form in your Blade view to upload the CSV/Excel file:
resources/views/import.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Import and Export CSV/Excel File in Laravel 12</title>
</head>
<body>
<h2>Import Users</h2>
<form action="/import" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file" required>
<button type="submit">Import</button>
</form>
<h2>Export Users</h2>
<a href="/export">Download Excel</a>
</body>
</html>
If you haven't already migrated your database, run the migration:
php artisan migrate
Start your Laravel development server:
php artisan serve
You might also like: