If you’re looking to seamlessly import and export CSV and Excel files into your database using Laravel apps, then the maatwebsite/excel package is the perfect tool for the job. In this tutorial, you will learn how to integrate and leverage the capabilities of the maatwebsite/excel package in your Laravel 10 web application.
So, In this tutorial, you will learn how to export and import CSV & excel files to MySQL database using maatwebsite/excel package in Laravel 10.
Laravel 10 Import Export CSV & Excel File Example
By using the following steps, You can import and export CSV, Excel files from the database with laravel 10 apps:
- Step 1 – Create New Laravel 10 Project
- Step 2 – Setup Database with Laravel 10 Project
- Step 3 – Install maatwebsite/excel Package
- Step 4 – Configure maatwebsite/excel
- Step 5 – Define Routes
- Step 6 – Define Import Export Class
- Step 7 – Create ImportExportExcelCSV Controller
- Step 8 – Create Import Export Form
- Step 9 – Run Development Server
Step 1 – Create New Laravel 10 Project
First of all, start your terminal to download or install Laravel 10 new setup. Execute the following command into it to install new Laravel 10 app into your system:
composer create-project --prefer-dist laravel/laravel ExcelCSVImportExport
Step 2 – Setup Database with Laravel 10 Project
In step 2, open your downloaded Laravel 10 app into any text editor. Then find .env file and configure database detail like the following:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=db name DB_USERNAME=db user name DB_PASSWORD=db password
Step 3 – Install maatwebsite/excel Package
Installing maatwebsite/excel package using the following command:
composer require maatwebsite/excel
Step 4 – Configure maatwebsite/excel
Configure maatwebsite/excel package in the app.php file. Open the app.php file, which is established inside the config directory.
'providers' => [ ....... ....... ....... Maatwebsite\Excel\ExcelServiceProvider::class, ], 'aliases' => [ ....... ....... ....... 'Excel' => Maatwebsite\Excel\Facades\Excel::class, ],
Then publish the config of maatwebsite/excel package by using the following command:
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
Step 5 – Define Routes
Open web.php file from routes direcotry. And update the following routes into web.php file:
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']);
Step 6 – Define Import Export Class
Create import and export excel csv class using the following commands:
For compose import class:
php artisan make:import UsersImport --model=User
Then update the following code into UsersImport.php class file, which is established at app/Imports directory:
<?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']), ]); } }
For compose export class:
php artisan make:export UsersExport --model=User
Then update the following code into UsersImport.php class file, which is established at app/Exports directory:
<?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(); } }
Step 7 – Create ImportExportExcelCSV Controller
Create ExcelCSV controller by using the following command:
php artisan make:controller ExcelCSVController
Now, visit your laravel directory app/http/controllers and open ExcelCSVController.php file. And update the following code into it:
<?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 10'); } /** * @return \Illuminate\Support\Collection */ public function exportExcelCSV($slug) { return Excel::download(new UsersExport, 'users.'.$slug); } }
Step 8 – Create Blade File
Create blade view file for import export excel and csv file from database. So, Go to resources/views directory and create excel-csv-import.blade.php and update the following code into it:
<!DOCTYPE html> <html> <head> <title>Laravel 10 Import Export Excel and CSV File To Database Example Tutorial - Tutsmake.com</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 10 - Tutsmake.com</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>
Step 9 – Run Development Server
Execute the following command on command prompt to start the development server:
php artisan serve
Then open your browser and hit the following url on it:
http://127.0.0.1:8000/excel-csv-file