Hello developers! Today I will show you, in the Laravel 12 application, how to import and export excel and csv files.
Here we may use the `maatwebsite/excel` composer package for import and export tasks. We will create a simple form for input where you can upload a CSV file and create multiple users in this example. Then, in an excel file, I will create an export route that will download all users from the database.
Therefore, we will follow some crucial steps below to create the import and export function and can export files with .csv, .xls, and .xlsx extensions in Laravel 12.
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
Execute the command below if you still have not created the Laravel app.
laravel new example-app
Step 2: Install maatwebsite/excel Package
Here 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 created to build import classes, which need to be used in the controller. Creating a new Import class is a great idea. 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' ]; } }
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. Run 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
Here, we will create a `UserController` with `index()`, `export()`, and `import()` methods. Therefore, first 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 steps have been completed; now you have to type the command given below and hit enter to run the Laravel app:
php artisan serve
Read More Blog Posts:
Laravel Pagination for Beginners
Laravel Database Seeding for Beginners (Laravel 12.x)
Laravel Migrations: Manage Your Database Migrations with Our Simple Guide
Open your web browser, type the given URL, and view the app output:
http://localhost:8000/users