Welcome to CodeCrew Infotech
In web development, managing large datasets can be a challenge, especially when dealing with file imports. Laravel Excel is a powerful package that simplifies Excel and CSV file handling in Laravel. Coupled with Laravel's queue system, you can efficiently manage these imports without affecting the performance of your application. This blog will guide you through the steps to implement queue jobs for importing data using Laravel Excel in Laravel 11.
Now, open a terminal and run this command:
composer create-project laravel/laravel excel-import-laravel
After Setup Project:
cd excel-import-laravel
Configuring database credentials for the Laravel application is essential. Simply update the .env file located in the root directory of the application:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=your_db_name DB_USERNAME=your_db_username DB_PASSWORD=your_db_password
Migrate the database using the following command:
php artisan migrate
Install the maatwebsite/excel package via Composer:
Now, open terminal
composer require maatwebsite/excel
Now, open terminal
php artisan make:model Product -m
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('products', function (Blueprint $table) { $table->id(); $table->string('name'); $table->text('description')->nullable(); $table->decimal('price', 8, 2); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('products'); } };
To begin, open your 'app/Models/Product.php' file and make the necessary modifications to the existing code.
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Product extends Model { protected $fillable = ['name', 'description', 'price']; }
Next, create a new job for importing Excel data. You can generate a new job using the Artisan command:
Here's the command:
php artisan make:job ImportExcelJob
This will create a new job class in the app/Jobs directory. Open the ImportExcelJob class and update it with the following code:
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\Product;
class ImportExcelJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $filePath;
public function __construct($filePath)
{
$this->filePath = $filePath;
}
public function handle()
{
$rows = Excel::toArray([], $this->filePath);
$headingRow = $rows[0][0]; // Get the heading row
$data = array_slice($rows[0], 1);
foreach ($data as $row) {
$rowData = array_combine($headingRow, $row);
$product = new Product([
'name' => $rowData['Name'],
'description' => $rowData['Description'],
'price' => $rowData['Price'],
]);
// Save the product
$product->save();
}
}
}
First, create the controller using the Artisan command:
php artisan make:controller ExcelController
<?php
namespace App\Http\Controllers;
use App\Jobs\ImportExcelJob;
use Illuminate\Http\Request;
class ExcelController extends Controller
{
/**
* Display the Excel import form.
*
* @return \Illuminate\View\View
*/
public function index()
{
return view('import');
}
/**
* Handle the Excel import request.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
public function import(Request $request)
{
$request->validate([
'excel_file' => 'required|file|mimes:xlsx,xls',
]);
$file = $request->file('excel_file');
$filePath = $file->getPathname();
ImportExcelJob::dispatch($filePath);
return redirect()->back()->with('success', 'Excel import job has been initiated.');
}
}
To begin, open your 'resources/views/layouts/app.blade.php' file and make the necessary modifications to the existing code.
<!DOCTYPE html>
<html>
<head>
<title>Laravel 11 Product Import</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>
create `resources/views/import.blade.php`
@extends('layouts.app')
@section('content')
<div class="card mt-5">
<h3 class="card-header">Product Import</h3>
<div class="card-body">
@session('success')
<div class="alert alert-success" role="alert">
{{ $value }}
</div>
@endsession
@if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('excel.import') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="excel_file" required>
<button class="btn btn-success" type="submit">Import Excel</button>
</form>
</div>
</div>
@endsection
To begin, open your 'routes/web.php' file and make the necessary modifications to the existing code.
<?php
use App\Http\Controllers\ExcelController;
use Illuminate\Support\Facades\Route;
Route::get('/', [ExcelController::class, 'index'])->name('excel.index');
Route::post('/import-excel', [ExcelController::class, 'import'])->name('excel.import');
Run the following command:
php artisan serve
Now, open your web browser and navigate to the provided URL to view the application output.
localhost:8000
Finally, you need to ensure that Laravel's queue workers are running and processing the jobs. You can start a worker using the following Artisan command:
php artisan queue:work
In conclusion, implementing Excel imports with Laravel Excel and queue jobs in Laravel 11 streamlines data management tasks efficiently. This setup ensures seamless handling of large datasets without compromising application performance, enhancing overall user experience and productivity.