Hello Laravel Friends,
Laravel is one of the most advanced PHP frameworks for web applications development. In case you are dealing with the data processing project you may use the Excel files import to Laravel application. Data importation is typical for Laravel application developments and one type is the import of Excel files.
Laravel 11 is lighter, more modern, and includes additional features. It still possesses concepts that Laravel developers already are familiar with.
In this tutorial, we’ll show you how you can export data from the Excel files or import data to Laravel 11 using Laravel Excel.
Prerequisites to Import Excel File in Laravel 11:
Before we dive into the tutorial, make sure you have the following prerequisites:
- Composer (latest Version)
- Laravel version 11
Steps to Import Excel File in Laravel 11:
Step 1: Create a New Laravel Project
Step 2: Install Laravel Excel
Step 3: Create a Controller
Step 4: Define the Import Logic
Step 5: Create an Import Class
Step 6: Create a Blade View
Step 7: Create a Route
Step 8: Test the Excel Import
Step 1: Create a New Laravel Project
Use the command below to create a new Laravel project.
composer create-project laravel/laravel:^11.0 excel-demo
cd excel-demo
Step 2: Install Laravel Excel
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:
composer require maatwebsite/excel:^3.1
This command will download and install the Laravel Excel package and its dependencies.
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:
php artisan make:controller ExcelImportController
This command will create an ExcelImportController.php file in the app/Http/Controllers directory.
Step 4: Define the Import Logic
Next, open the newly created ExcelImportController.php file, and set up the import logic in a method. For example, let’s create a method named import:
// app/Http/Controllers/ExcelImportController.php
<?php
namespace App\Http\Controllers;
use App\Imports\MyImporter;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\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 MyImporter, $file);
return redirect()->back()->with('success', 'Excel file imported successfully!');
}
}
In this code, you first have to check if the uploaded file is .xlsx or .xls, then you can validate other elements according to your needs. Using the following import method, we would handle the Excel file through the import class that we will create in the next step, by calling the Excel::import method.
Step 5: Create an Import Class
Here, you must create an import class that identifies how to import data from the Excel file. Run the command below to generate an import class:
php artisan make:import MyImporter
This command creates a file in the app/Imports directory. In the file, you can now create the import logic. Below is how that could look like:
<?php
namespace App\Imports;
use App\Models\User;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToModel;
class MyImporter implements ToModel
{
private $rowNumber = 0;
public function model(array $row)
{
$this->rowNumber++;
// Define how to create a model from the Excel row data
if ($this->rowNumber == 1) {
return null; // Do nothing for the first row
}
return new User([
'name' => $row[1],
'email' => $row[2],
// Add more columns as needed
]);
}
}
In this code, the model method indicates where to create a model for each row of the Excel file. Adjust the method as per your Excel file’s structures and your Laravel model.
Step 6: Create a Blade View
Next, generate a Blade view that enables the user to upload the Excel file. Here’s a simple example:
<!DOCTYPE html>
<body>
<h1>Excel demo</h1>
@if(session('success'))
<div class="alert alert-success" style="color:green;font-size:16px;font-weight:400">
{{ 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>
</body>
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:
// routes/web.php
Route::post('/import-excel', [ExelImportController::class, 'index'])→name('import.excel');
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:
php artisan serve
Output:
Now, ho to port 8000 (Default) and choose the excel file and click on import button, you will see the success message in green color.
Conclusion:
In this Laravel 11 tutorial, we learned how to import Excel file using the Laravel Excel package inside the Laravel framework. What we learned here includes installation, setting up the package, implementing the controller and an importing class, a Blade view for creating files, defining routes for all these steps, and we are ready to test the file importing process.
This feature becomes very handy in case of really large datasets or if you intend to import data from a spreadsheet in Excel into your application. You may, of course, tailor this code as needed for your project, and thus you will be armed with a very robust Excel import function in your Laravel application.
If you feel that you are stuck anywhere, you are free to reach me at the comment box or Hire Experienced Laravel Developers to help you with many different aspects of your Laravel project.
Happy Coding!
FAQ
- Which package is best for importing Excel files in Laravel 11?
The most recommended package is Maatwebsite/Laravel-Excel.
- What file types can I import?
You can import .xlsx, .xls, and .csv files.
- Why do I need to import Excel files in Laravel?
Importing Excel files helps quickly upload bulk data (like users, products, orders, or inventory) into the database without manually entering each record.