Import Export to Excel and CSV using Maatwebsite in Laravel 5
In this section, we are going to use Maatwebsite so that we can import-export to CSV and Excel. We will use Laravel 5 to do this. We will use a database to store the imported CSV or Excel file. By using the Maatwebsite, we can download or export CSV or Excel files from the table of our database.
We can easily get the data by using the package of Maatwebsite. It is also useful to group by data, and we can create multiple sheets. In our below example, we have described the items table data. We can use CSV, XLS, and XLSV format to download it, and we can also use the file of CSV, XLS, and XLSX to import the data. In our Laravel 5 project, we can implement export and import function by following the step by step process, which is described as follows:
In this step, we will do Installation. We will use our file named composer.json and then use the required package and put the following line into it according to our Laravel version.
Now we will run the following command:
Now we will use our file named config/app.php, and then we will add the aliase and service provider into it:
We will use the below command if we use Laravel 5 like this:
We will use the below command if we use Laravel 4 like this:
In order to create a config file, this command will be very useful. This file will be used in the excel package.
In the second step, we are going to Create Table and Model. We will use the item table to create a migration. We will create this by using the php artisan command of Laravel 5, which is described as follows:
When we successfully execute the above command, we will use the database/migrations path to get the one file. Now we will use our migration file and add the following code into it to create item tables like this:
When we successfully create this “items” table, we need to create an Item model. For this, we will use the app/Item.php path, and then we will add the following code into it:
In this step, we are going to Create Route. We will create this for the import-export file. For this, we will use our file named app/Http/routes.php, and then we will put the below route:
In this file, we are going to Create Controller. We will Create MaatwebsiteDemoController as a new controller. We will use the app/Http/Controllers/MaatwebsiteDemoController.php path to create this controller. All importExcel requests, importExport, return response, and downloadExcel can be managed by this controller. Now we will use the controller file and add the following content into it:
In this step, we are going to Create View. We will create layout by creating the file named importExport.blade.php. This file will be useful to write the design code. We will add the below code into that file:
Now our above script is ready to run. In order to run the above script quickly, we will use our browser. When we open the browser, we will see the preview like this: