DEV Community

Cover image for How To Import And Export Excel And Csv Files In Laravel 12
Msh Sayket
Msh Sayket

Posted on

1 1 1 1 1

How To Import And Export Excel And Csv Files In Laravel 12

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
User::factory()->count(10)->create()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Read Full Tutorials

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs