Laravel 8 Import Export Excel and CSV File Tutorial
Tags: Maatwebsite, Import Export, Laravel Framework, Laravel, PHP

Often we may need to create or download bulk records in our application. In this tutorial, we will learn how to import and export Excel/CSV file into database in Laravel 8.0 using MaatWebsite 3.1. Grab the base source code from previous tutorial.

Installation

Run the command below to download and install the require package.

composer require maatwebsite/excel

Add the ServiceProvider and alias in config/app.php

'providers' => [

/*

* Package Service Providers...

*/

Maatwebsite\Excel\ExcelServiceProvider::class,

] 'aliases' => [

...

'Excel' => Maatwebsite\Excel\Facades\Excel::class,

]

Now, use the following command to publish the package configuration file.

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config

This will create a configuration file names “config/excel.php”.

Create Import Class

We need to create an Import class, this Import object encapsulate the importing logic and handling.

php artisan make:import ProductsImport --model=Product

Command above will create a ProductsImport class associate to our Product model and can be found in app/Imports directory.

<?php namespace App\Imports; use App\Models\Product;

use Illuminate\Support\Facades\Hash;

use Maatwebsite\Excel\Concerns\ToModel; class ProductsImport implements ToModel

{

/**

* @param array $row

*

* @return User|null

*/

public function model(array $row)

{

return new Product([

'title' => $row[0],

'description' => $row[1],

'price' => $row[2],

]);

}

}

Create Export Class

Run the command below to create a Product Export class. An ProductsExport class will be created in app/exports.

php artisan make:export ProductsExport --model=Product <?php namespace App\Exports; use App\Models\Product;

use Maatwebsite\Excel\Concerns\FromCollection; class ProductsExport implements FromCollection

{

/**

* @return \Illuminate\Support\Collection

*/

public function collection()

{

return Product::all();

}

}

Integrate with Controller

We can implement two more functions in ProductController.

...

use Maatwebsite\Excel\Facades\Excel;

use App\Exports\ProductsExport;

use App\Imports\ProductsImport;

... public function import(Request $request)

{

Excel::import(new ProductsImport(), $request->file('file')); return redirect()->route('product.index')

->with('success', 'Products has been imported');

} public function export()

{

return Excel::download(new ProductsExport, 'products.xlsx');

}

...

Create New Route

Now, create two new routes to import and export product records.

...

Route::post('product/import', [ProductController::class, 'import'])->name('product.import');

Route::get('product/export', [ProductController::class, 'export'])->name('product.export');

...

** Please note that, you need to define those routes before your call to Route::resource

Import View

Insert the code snippet below into product/index.blade.php

...

<div class="modal fade" id="importmodal" aria-labelledby="importModalLabel" aria-hidden="true">

<div class="modal-dialog">

<div class="modal-content">

<div class="modal-header">

<h5 class="modal-title" id="importModalLabel">Import Products</h5>

<button type="button" class="close" data-dismiss="modal" aria-label="Close">

<span aria-hidden="true">×</span>

</button>

</div>

<form id="import_product_modal" action="{{ route('product.import') }}" method="POST" enctype="multipart/form-data">

@csrf

<div class="modal-body">

<div class="row">

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Upload File:</strong>

<input type="file" name="file" id="file" class="form-control"/>

</div>

</div>

</div>

</div>

<div class="modal-footer">

<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

<button type="submit" class="btn btn-primary">Import</button>

</div>

</form>

</div>

</div>

</div>

... // Create two button to trigger the actions

<a class="btn btn-primary" href="#" id="productimportbtn">Import Products</a> <a class="btn btn-primary" href="{{ route('product.export') }}" id="productexportbtn">Export Products</a> <script>

...

$('#productimportbtn').on('click', function() {

$('#importmodal').modal('show');

});

...

</script>

Contact me @ sgwebfreelancer@gmail.com if you need the full source code.