To import an Excel file in Laravel, you can follow these steps:
Step 1:
Install Required "maatwebsite/excel" package Package by running below command
//code starting
composer require maatwebsite/excel
//code ending
Step 2:
Go to config/app.php file and and add following providers
'providers' => [
// ...
Maatwebsite\Excel\ExcelServiceProvider::class,
],
Step 3:
And then Alias
'aliases' => [
...
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]
Step 4:
Run following command
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
Step 5:
If you got an error while publishing edit version of "maatwebsite/excel"
"maatwebsite/excel": "^3.1.48"
You can update version by using composer.json file
Step 6:
You'll have enable following extesions to use "maatwebsite/excel"
PHP extension php_zip enabled
PHP extension php_xml enabled
PHP extension php_gd2 enabled
PHP extension php_iconv enabled
PHP extension php_simplexml enabled
PHP extension php_xmlreader enabled
PHP extension php_zlib enable
Step 7:
To enable php extension go to the directory where you have php installed then
- go to bin folder
- then search for php.ini file
then uncomment zip and other extension
Step 8:
Create an Import Class
Create a new import class that will handle the logic for importing the Excel file. You can generate this class using the following Artisan command:
//code starting
php artisan make:import UsersImport --model=User
//code ending
Replace UsersImport with the desired name of your import class and User with the corresponding model name
Example I'm using TodosImport and Todo model so I'll use following code
//code starting
php artisan make:import TodosImport --model=Todo
//code ending
Step 9:
Implement Import Logic
Open the generated import class (e.g., app/Imports/UsersImport.php) and update the import() method with the logic to handle the imported data. Here's an example of how it might look:
//code starting
<?php
namespace App\Imports;
use App\Models\Todo;
use Maatwebsite\Excel\Concerns\ToModel;
class TodosImport implements ToModel
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new Todo([
'task' => $row[0],
'status' => $row[1],
]);
}
}
//code ending
Step 10:
Create a TodoController and migraions and model using below command
//code starting
php artisan make:model Todo -mcr
//code ending
Step 11:
Update migration file
//code starting
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('todos', function (Blueprint $table) {
$table->id();
$table->string('task');
$table->string('status');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('todos');
}
};
//code ending
Step 12:
Update Model File 'Todo.php'
//code starting
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('todos', function (Blueprint $table) {
$table->id();
$table->string('task');
$table->string('status');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('todos');
}
};
//code ending
Step 13:
Update Controller File 'TodoController.php'
//code starting
<?php
namespace App\Http\Controllers;
use App\Models\Todo;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\TodosImport;
class TodoController extends Controller
{
/**
* Display a listing of the resource.
*/
public function import(Request $request)
{
$file = $request->file('excel_file');
$this->validate($request, [
'excel_file' => 'required|mimes:xlsx,xls'
]);
try {
Excel::import(new TodosImport, $file);
return redirect()->back()->with('success', 'Data Imported! ');
} catch (Exception $e) {
return redirect()->back()->with('error', 'Error importing data: ', $e->getMessage());
}
}
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*/
public function show(Todo $todo)
{
//
}
/**
* Show the form for editing the specified resource.
*/
public function edit(Todo $todo)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, Todo $todo)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy(Todo $todo)
{
//
}
}
//code ending
Step 14:
Create an Import Class
Create a new import class that will handle the logic for importing the Excel file. You can generate this class using the following Artisan command:
//code starting
php artisan make:import TodosImport --model=Todo
//code ending
Step 15:
Implement Import Logic
Open the generated import class (e.g., app/Imports/TodosImport.php) and update the import() method with the logic to handle the imported data. Here's an example of how it might look:
//code starting
<?php
namespace App\Imports;
use App\Models\Todo;
use Maatwebsite\Excel\Concerns\ToModel;
class TodosImport implements ToModel
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new Todo([
'task' => $row[0],
'status' => $row[1],
]);
}
}
//code ending
Step 16:
Update routes by updating web.php file
//code starting
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TodoController;
Route::get('/', function () {
return view('welcome');
});
Route::get('/import', function () {
return view('import');
});
Route::post('/import-excel', [TodoController::class, 'import'])->name('import.excel');
//code ending
Step 17:
Create a Form to Upload the File
Create a form in your Laravel application to allow users to upload the Excel file. Here's an example of a simple form:
I have create a import.blade.php file to import excel file
//code starting
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
<!-- Fonts -->
<link rel="preconnect" href="https://fonts.bunny.net">
<link href="https://fonts.bunny.net/css?family=figtree:400,600&display=swap" rel="stylesheet" />
<script src="https://cdn.tailwindcss.com"></script>
<!-- Styles -->
</head>
<body class="antialiased">
<div class="container mx-auto">
<div class="flex justify-center">
<div class="w-8/12">
<div class="bg-white rounded-lg shadow-md">
<div class="py-4 px-6 bg-gray-100 border-b">
Import Excel
</div>
<div class="p-6">
@if (session('success'))
<div class="bg-green-100 text-green-600 border border-green-400 px-4 py-3 rounded relative mb-4" role="alert">
{{ session('success') }}
</div>
@endif
@if (session('error'))
<div class="bg-red-100 text-red-600 border border-red-400 px-4 py-3 rounded relative mb-4" role="alert">
{{ session('error') }}
</div>
@endif
<form action="{{ route('import.excel') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="mb-4">
<label for="excel_file" class="block mb-2">Excel File</label>
<input type="file" id="excel_file" name="excel_file" class="py-2 px-4 border border-gray-300 rounded">
@error('excel_file')
<small class="text-red-500">{{ $message }}</small>
@enderror
</div>
<button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded">Import</button>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
//code ending
Step 18:
Test the Import
Now, when you navigate to the page containing the import form, you can select an Excel file and submit the form. The file will