Hello Laravel Friends,
Laravel is a powerful PHP framework that simplifies web application development. If your project involves handling data, you might need to import data from Excel files into your Laravel application. Importing Excel files into a Laravel application can be a common task, especially when dealing with data imports from various sources.
In this tutorial, I’ll guide you through the process of importing Excel files in Laravel using the popular Laravel Excel package.
Contents
Prerequisites to Import Excel File in Laravel:
Before we dive into the tutorial, make sure you have the following prerequisites:
- A Laravel project set up and running.
- Basic knowledge of Laravel’s Eloquent ORM and Blade templating engine.
- Composer installed on your system.
Steps to Import Excel File in Laravel:
Step 1: Install Laravel Excel
To get started, you’ll need to install the Laravel Excel package. Open your terminal and navigate to your Laravel project’s root directory. Then, run the following command:
1 |
composer require maatwebsite/excel |
This command will download and install the Laravel Excel package and its dependencies.
Step 2: Configure the Package
After installation, you need to configure the Laravel Excel package. Open the config/app.php file and add the following service provider and alias to the providers and aliases arrays, respectively:
1 2 3 4 5 6 7 8 9 10 11 |
// config/app.php 'providers' => [ // ... Maatwebsite\Excel\ExcelServiceProvider::class, ], 'aliases' => [ // ... 'Excel' => Maatwebsite\Excel\Facades\Excel::class, ], |
Next, publish the package configuration file by running the following command:
1 |
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" |
This command will create a config/excel.php file where you can customize your Excel import settings.
Step 3: Create a Controller
Now, let’s create a controller to handle the Excel file import. Run the following command to generate a new controller:
1 |
php artisan make:controller ExcelImportController |
This command will create a file named ExcelImportController.php in the app/Http/Controllers directory.
Step 4: Define the Import Logic
Open the ExcelImportController.php file and define the import logic in a method. For example, let’s create a method named import:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// app/Http/Controllers/ExcelImportController.php use Excel; class ExcelImportController extends Controller { public function import(Request $request) { // Validate the uploaded file $request->validate([ 'file' => 'required|mimes:xlsx,xls', ]); // Get the uploaded file $file = $request->file('file'); // Process the Excel file Excel::import(new YourImportClass, $file); return redirect()->back()->with('success', 'Excel file imported successfully!'); } } |
In this code, we first validate that the uploaded file is of type .xlsx or .xls. You can adjust the validation rules according to your needs. Next, we use the Excel::import method to process the Excel file using an import class that we’ll create in the next step.
Step 5: Create an Import Class
You need to create an import class that specifies how the data from the Excel file should be imported. Run the following command to generate an import class:
1 |
php artisan make:import YourImportClass |
This command will create a file in the app/Imports directory. Open this file and define the import logic. Here’s an example of how it might look:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// app/Imports/YourImportClass.php namespace App\Imports; use Maatwebsite\Excel\Concerns\ToModel; class YourImportClass implements ToModel { public function model(array $row) { // Define how to create a model from the Excel row data return new YourModel([ 'column1' => $row[0], 'column2' => $row[1], // Add more columns as needed ]); } } |
In this code, the model method specifies how to create a model from the data in each row of the Excel file. You should adjust this method to match your Excel file’s structure and your Laravel model.
Step 6: Create a Blade View
Now, create a Blade view that allows users to upload the Excel file. Here’s a simple example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!-- resources/views/excel-import.blade.php --> @extends('layouts.app') @section('content') <div class="container"> @if(session('success')) <div class="alert alert-success"> {{ session('success') }} </div> @endif <form action="{{ route('import.excel') }}" method="POST" enctype="multipart/form-data"> @csrf <div class="form-group"> <label for="file">Choose Excel File</label> <input type="file" name="file" id="file" class="form-control"> </div> <button type="submit" class="btn btn-primary">Import</button> </form> </div> @endsection |
This Blade view includes a form with a file input field for uploading Excel files. It also displays a success message if the import is successful.
Step 7: Create a Route
In your web.php file (located in the routes directory), define a route for the Excel import view and the import action:
1 2 3 4 |
// routes/web.php Route::get('/import-excel', 'ExcelImportController@index')->name('import.excel'); Route::post('/import-excel', 'ExcelImportController@import'); |
Step 8: Test the Excel Import
With everything set up, you can now test your Excel import feature. Start your Laravel development server by running:
1 |
php artisan serve |
Visit the Excel import page in your browser, usually at http://localhost:8000/import-excel. Upload an Excel file, and if everything is configured correctly, the data should be imported into your database.
Conclusion:
In this tutorial, we’ve demonstrated how to import Excel files in Laravel using the Laravel Excel package. You learned how to install and configure the package, create a controller and an import class, set up a Blade view for file uploads, define routes, and test the import process.
This feature can be immensely valuable when dealing with large datasets or when migrating data from Excel spreadsheets into your Laravel application. Feel free to customize the code to fit your specific project requirements, and you’ll have a robust Excel import functionality integrated into your Laravel application.
In case you are stuck anywhere, connect with me through the comment box or Hire Experienced Laravel Developers to help you with various aspects of your Laravel project.
Happy Coding!