Laravel 5.6 – Import Export excel file using Maatwebsite

maatwebsite laravel-excel

Maatwebsite Laravel Excel is a popular package for importing and exporting data to and from excel or csv file. I will explain step by stem using this package in our laravel application. When you are working with large datasets, you need to import or export data from your database to external file. For this, Maatwebsite Laravel Excel is a perfect package. From the official documentation, Laravel Excel features are:

  • Easily export collections to Excel
  • Export queries with automatic chunking for better performance
  • Queue exports for better performance
  • Easily export Blade views to Excel

Let’s get started integrating.

Installing Package

You can install the package using Composer by running the below command on your terminal.

This will download the package and PhpSpreadSheet in our application. Now, add ServiceProvider in App/Config/app.php

Similarly, add Alias in the same file in alias array section.

After these settings are saved, publish the configuration files. To do this, run the below command.

Create Countries Table and Models

We will create a migration file to create a table named ‘countries’. To create it, run the following command in your terminal:

It creates a migration file under database/migrations. Open it and make some changes in up() function to fit according to our needs. The changed file looks like:

Now, run the migration to create table. For this, run the following command.

After creating table, let’s create Model for this table. Run the following command:

This will create a Country Model inside App/Models/ directory. Open the model and make fields of table fillable as like below:

Create Route
Add some routes for uploading csv file and for downloading files. Simply add the below routes in your routes/web.php file.

Create Controller

Now, create a controller file for processing our application logic. All our importing and exporting functionalities will be handled with this controller file named ExcelController.php. To create it, run the following command:

We have to make some changes to this controller. Final controller file looks like below:

Create View

We have successfully setup our controller, now let’s create view to upload and download file. Create a new default template as default.blade.php inresources/views/layouts

Now, our application is ready to import any excel file and export database to any excel file. If you need countries excel file, you can download from this link.
Hope you find it helpful  .