Laravel 12 Import Export Excel and CSV File Example
In this example, I will show you how to import and export excel and csv files in the laravel 12 application.
We will use the `maatwebsite/excel` composer package for import and export tasks. In this example, we will create a simple form for input where you can upload a CSV file and create multiple users. Then, I will create an export route that will download all users from the database in an Excel file.
So, let's follow the steps below to create the import and export function in a Laravel 12 application. You can export files with .csv, .xls, and .xlsx extensions.
Step for Laravel 12 Import Export CSV File Example
- Step 1: Install Laravel 12
- Step 2: Install maatwebsite/excel Package
- Step 3: Create Dummy Records
- Step 4: Create Import Class
- Step 5: Create Export Class
- Step 6: Create Controller
- Step 7: Create Routes
- Step 8: Create Blade File
- Run Laravel App
Step 1: Install Laravel 12
This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:
laravel new example-app
Step 2: Install maatwebsite/excel Package
In this step, we need to install the `maatwebsite/excel` package via the Composer package manager. Open your terminal and enter the following command:
composer require maatwebsite/excel
Step 3: Create Dummy Records
In this step, we will create some dummy records for the users table so we can export them later. Let's run the following Tinker command:
php artisan tinker
User::factory()->count(10)->create()
Step 4: Create Import Class
In Maatwebsite version 3, a way is provided to build import classes, which need to be used in the controller. It would be a great idea to create a new Import class. So, you have to run the following command and make the necessary changes to the code in that file:
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:5',
'email' => 'required|email|unique:users'
];
}
}
You can download the demo CSV file from here: Demo CSV File.
Step 5: Create Export Class
Maatwebsite version 3 provides a way to build export classes, which we use in the controller. It's a great way to create a new Export class. To do this, you have to run the following command and change the code in that file:
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"];
}
}
Step 6: Create Controller
In this step, we will create a `UserController` with `index()`, `export()`, and `import()` methods. So, first, let's create the controller by using the following command and update the code in it.
php artisan make:controller UserController
Now, update the code in the UserController file.
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)
{
// Validate incoming request data
$request->validate([
'file' => 'required|max:2048',
]);
Excel::import(new UsersImport, $request->file('file'));
return back()->with('success', 'Users imported successfully.');
}
}
Step 7: Create Routes
In this step, we need to create routes for the list of users, importing users, and exporting users. So, open your `routes/web.php` file and add the following route.
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');
Step 8: Create Blade File
In the last step, let's create `users.blade.php` (`resources/views/users.blade.php`) for the layout. We will write design code here and put the following code:
resources/views/users.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 12 Import Export Excel to Database Example - ItSolutionStuff.com</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/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 12 Import Export Excel to Database Example - ItSolutionStuff.com</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>
Run Laravel App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8000/users
Output:
I hope this can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel 12 REST API Authentication using Sanctum Tutorial
- Laravel 12 Generate PDF File using DomPDF Example
- Laravel 12 Image Upload Example Tutorial
- Laravel 12 CRUD Application Example Tutorial
- Laravel 12 NEW Starter Kits
- Laravel 12 Installation & New Features Overview
- How to Create PDF using Headless Chrome in Laravel?
- How to Convert Word Docx to PDF in Laravel?
- How to Page Break in PDF using DomPDF Laravel?
- How to Add Two Factor Authentication with SMS in Laravel?
- Laravel Send SMS to Mobile with Nexmo Example
- How to Send SMS using Twilio in Laravel?