In this tutorial will learn how to easily import and export Excel and CSV files in the Laravel 8 application while communicating with the PHP MySQL database using Maatwebsite/Laravel-Excel package.
Step 1: Install Laravel Project
composer create-project --prefer-dist laravel/laravel laravel-excel
Step 2: Configure Database Details
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=<DATABASE NAME>
DB_USERNAME=<DATABASE USERNAME>
DB_PASSWORD=<DATABASE PASSWORD>
Step 3: Install maatwebsite/excel package
composer require maatwebsite/excel
Next go to config/app.php and paste below code
'providers' => [
Maatwebsite\Excel\ExcelServiceProvider::class,
],
'aliases' => [
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
Step 4: Generate Fake Data and Migrate Table
php artisan migrate
php artisan tinker
After Opening the tinker, you need to run this command to generate the fake records in our database.
User::factory()->count(100)->create();
Step 5: Create a Routes
In this step, We will add a route to handle requests for import and export files.
use App\Http\Controllers\UserController;
Route::get('/file-import',[UserController::class,'importView'])->name('import-view');
Route::post('/import',[UserController::class,'import'])->name('import');
Route::get('/export-users',[UserController::class,'exportUsers'])->name('export-users');
Step 6: Create Import Class
php artisan make:import ImportUser --model=User
And put below code as well.
<?php
namespace App\Imports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
class ImportUser implements ToModel
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => bcrypt($row[2]),
]);
}
}
Step 7: Create Export Class
php artisan make:export ExportUser --model=User
<?php
namespace App\Exports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class ExportUser implements FromCollection
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return User::select('name','email')->get();
}
}
Step 8: Create Controller
php artisan make:controller UserController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ImportUser;
use App\Exports\ExportUser;
use App\Models\User;
class UserController extends Controller
{
public function importView(Request $request){
return view('importFile');
}
public function import(Request $request){
Excel::import(new ImportUser, $request->file('file')->store('files'));
return redirect()->back();
}
public function exportUsers(Request $request){
return Excel::download(new ExportUser, 'users.xlsx');
}
}
Step 9: Create Blade / View Files
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel 8 Import Export Excel & CSV File - TechvBlogs</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5 text-center">
<h2 class="mb-4">
Laravel 8 Import Export Excel & CSV File - <a href="https://techvblogs.com/blog/laravel-import-export-excel-csv-file?ref=repo" target="_blank">TechvBlogs</a>
</h2>
<form action="{{ route('import') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="form-group mb-4">
<div class="custom-file text-left">
<input type="file" name="file" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
<button class="btn btn-primary">Import Users</button>
<a class="btn btn-success" href="{{ route('export-users') }}">Export Users</a>
</form>
</div>
</body>
</html>
Run Laravel Application
php artisan serve
After executing this command, Open http://127.0.0.1:8000/file-import in your browser.
[…] Laravel 9 Import Export Excel & CSV File Example […]