In this example, I will show you how to import and export excel and csv files in laravel 12 application.
We will use the maatwebsite/excel
composer package for import and export tasks. In this example, we will create a simple form for input where you can upload a CSV file and create multiple users. Then, I will create an export route that will download all users from the database in an Excel file.
So, let’s follow the steps below to create the import and export function in a Laravel 12 application. You can export files with .csv, .xls, and .xlsx extensions. You Can Learn How to add form validation in laravel 12 Example
How To Import And Export Excel And Csv Files In Laravel 12 Example
Step 1: Install Laravel 12
This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:
laravel new example-app
Step 2: Install maatwebsite/excel Package
In this step, we need to install the maatwebsite/excel
package via the Composer package manager. Open your terminal and enter the following command:
composer require maatwebsite/excel
Step 3: Create Dummy Records
In this step, we will create some dummy records for the users table so we can export them later. Let’s run the following Tinker command:
php artisan tinker
User::factory()->count(10)->create()
Step 4: Create Import Class
In Maatwebsite version 3, a way is provided to build import classes, which need to be used in the controller. It would be a great idea to create a new Import class. So, you have to run the following command and make the necessary changes to the code in that file:
php artisan make:import UsersImport --model=User
Top comments (0)