In this tutorial you will learn about the Laravel 9 Import Export Excel & CSV File and its application with practical example.
In this Laravel 9 Import Export Excel & CSV File tutorial, I’ll show you how to import and export excel/csv file into and from database in laravel 9 using maatwebsite version 3 package with example. I’ll guide you through step by step with example of importing and exporting a csv or excel file using maatwebsite/excel version 3 composer package.
Laravel 9 Import Export Excel & CSV File
When we are developing laravel applications, there may situations where we require to import or export large amount of data into and from the application database. Importing and exporting data through excel or csv files seems a good solution here.
In laravel, maatwebsite/excel composer package made it easy to import or export excel or csv files. The maatwebsite/excel is a composer package used to import and export excel or csv files. The maatwebsite/excel provide number of features for excel or csv file import and exort in laravel.
Import and Export CSV and Excel File in Laravel 9
In this step by step Laravel 9 Import Export Excel & CSV File example I’ll demonstrate the import and export of csv file in laravel 9. Please follow the steps given below:
- Install Laravel 9
- Database Configuration
- Install maatwebsite/excel Package
- Configure maatwebsite/excel
- Create Routes
- Compose Import Export Class
- Create ExcelCSV Controller By Artisan Command
- Create Import Export Form
- Run Development Server
Install Laravel 9
First of all we need to create a fresh laravel project, download and install Laravel 9 using the below command
1 |
composer create-project --prefer-dist laravel/laravel lara9blog |
Configure Database In .env file
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
.env
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=lara9blog DB_USERNAME=root DB_PASSWORD= |
Install maatwebsite/excel Package
In this step we will install maatwebsite/excel Package. Use the following compose command to install maatwebsite/excel Package:
1 |
composer require maatwebsite/excel |
Configure Maatwebsite Package
After Installing Maatwebsite package, we need to add service provider and alias in config/app.php file as following.
config/app.php
1 2 3 4 5 6 7 8 9 10 11 |
'providers' => [ ....... Maatwebsite\Excel\ExcelServiceProvider::class, ], 'aliases' => [ ....... 'Excel' => Maatwebsite\Excel\Facades\Excel::class, ], |
Now, use following command to publish Maatwesite Package configuration file:
1 |
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" |
Create Routes
After this, we need to add following routes in “routes/web.php” file along with a resource route. Lets open “routes/web.php” file and add following route.
routes/web.php
1 2 3 4 5 |
use App\Http\Controllers\ExcelCSVController; Route::get('excel-csv-file', [ExcelCSVController::class, 'index']); Route::post('import-excel-csv-file', [ExcelCSVController::class, 'importExcelCSV']); Route::get('export-excel-csv-file/{slug}', [ExcelCSVController::class, 'exportExcelCSV']); |
Compose Import Export Class
Now, we need to create import and export excel csv class using the following commands:
Import class:-
1 |
php artisan make:import UsersImport --model=User |
Now, we have to update the UsersImport.php class file located at app/Imports directory. Let’s open UsersImport.php file and put the following code in it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php namespace App\Imports; use App\Models\User; use Maatwebsite\Excel\Concerns\ToModel; use Maatwebsite\Excel\Concerns\WithHeadingRow; class UsersImport implements ToModel, WithHeadingRow { /** * @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']), ]); } } |
export class:-
1 |
php artisan make:export UsersExport --model=User |
Now, we have to update UsersExport.php class file located at app/Exports directory. Let’s open UsersExport.php file and put the following code in it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php namespace App\Exports; use App\Models\User; use Maatwebsite\Excel\Concerns\FromCollection; class UsersExport implements FromCollection { /** * @return \Illuminate\Support\Collection */ public function collection() { return User::all(); } } |
Create Import Excel Controller
Next, we have to create a controller to display a form to upload excel file records. Lets Create a controller named ExcelCSVController using command given below –
1 |
php artisan make:controller ExcelCSVController |
Once the above command executed, it will create a controller file ExcelCSVController.php in app/Http/Controllers/ directory. Open the ExcelCSVController.php file and put the following code in it.
app/Http/Controllers/ExcelCSVController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Exports\UsersExport; use App\Imports\UsersImport; use Maatwebsite\Excel\Facades\Excel; use App\Models\User; class ExcelCSVController extends Controller { /** * @return \Illuminate\Support\Collection */ public function index() { return view('excel-csv-import'); } /** * @return \Illuminate\Support\Collection */ public function importExcelCSV(Request $request) { $validatedData = $request->validate([ 'file' => 'required', ]); Excel::import(new UsersImport,$request->file('file')); return redirect('excel-csv-file')->with('status', 'The file has been excel/csv imported to database in laravel 8'); } /** * @return \Illuminate\Support\Collection */ public function exportExcelCSV($slug) { return Excel::download(new UsersExport, 'users.'.$slug); } } |
Create Blade / View Files
In this step, we will create view/blade file to import export excel and csv file. Lets create a blade file “excel-csv-import.blade.php” in “resources/views/” directory and put the following code in it respectively.
resources/views/excel-csv-import.blade.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<!DOCTYPE html> <html> <head> <title>Laravel 9 Import Export Excel and CSV File To Database Example Tutorial</title> <meta name="csrf-token" content="{{ csrf_token() }}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> </head> <body> <div class="container mt-5"> @if(session('status')) <div class="alert alert-success"> {{ session('status') }} </div> @endif <div class="card"> <div class="card-header font-weight-bold"> <h2 class="float-left">Import Export Excel, CSV File In Laravel 8</h2> <h2 class="float-right"><a href="{{url('export-excel-csv-file/xlsx')}}" class="btn btn-success mr-1">Export Excel</a><a href="{{url('export-excel-csv-file/csv')}}" class="btn btn-success">Export CSV</a></h2> </div> <div class="card-body"> <form id="excel-csv-import-form" method="POST" action="{{ url('import-excel-csv-file') }}" accept-charset="utf-8" enctype="multipart/form-data"> @csrf <div class="row"> <div class="col-md-12"> <div class="form-group"> <input type="file" name="file" placeholder="Choose file"> </div> @error('file') <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div> @enderror </div> <div class="col-md-12"> <button type="submit" class="btn btn-primary" id="submit">Submit</button> </div> </div> </form> </div> </div> </div> </body> </html> |
Run Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Now, open the following URL in browser to see the output –
1 |
http://localhost:8000/excel-csv-file |