How to Insert Data using Excel Upload in Laravel 11 ?
In this tutorial I’m going to learn how to insert data using upload excel file in Laravel 12 &11.
Step 1: Install the Laravel Application and setup the database.
Step 2: Install Laravel Excel Package via composer.
composer requiremaatwebsite/excel
php artisan make:model Customer -m
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
Next go to Customer model and put the below code
protected $fillable = ['name','email','phone'];
Next go to migration and add below code.
public function up(): void
{
Schema::create('customers', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email');
$table->string('phone');
$table->timestamps();
});
}
Next migrate the table
php artisan migrate
php artisan make:import CustomerImport
<?php
namespace App\Imports;
use App\Models\Customer;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class CustomerImport implements ToCollection, WithHeadingRow
{
/**
* @param Collection $rows
*/
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
if (!$row['email']) {
continue;
}
$customer = Customer::where('email', $row['email'])->first();
if($customer){
$customer->update([
'name' => $row['name'],
'phone' => $row['phone'],
]);
}else{
Customer::create([
'name' => $row['name'],
'email' => $row['email'],
'phone' => $row['phone'],
]);
}
}
}
}
Next to Create Controller
php artisan make:controller CustomerController
<?php
namespace App\Http\Controllers;
use App\Models\Customer;
use Illuminate\Http\Request;
use App\Imports\CustomerImport;
use Maatwebsite\Excel\Facades\Excel;
class CustomerController extends Controller
{
public function index()
{
$customers = Customer::all();
return view('customer.index', compact('customers'));
}
public function importExcelData(Request $request)
{
$request->validate([
'import_file' => [
'required',
'file'
],
]);
Excel::import(new CustomerImport, $request->import_file);
return redirect()->back()->with('status', 'Imported Successfully');
}
}
Next go to web.php and put the below code.
Route::get('customer/import', [App\Http\Controllers\CustomerController::class, 'index']);
Route::post('customer/import', [App\Http\Controllers\CustomerController::class, 'importExcelData'])->name('importExcelData');
Next to run project using below command
php artisan serve
http://127.0.0.1:8000/customer/import/
Upload excel and click on Import Button, then your data insert in database.
Successfully data inserted in database.
Thanks for learning 🙏🙏.