Laravel 11 Import Excel and CSV File Tutorial

Laravel 11 Import Excel and CSV File Tutorial

Maatwebsite/Excel is a popular Laravel package that allows users to import and export data from Excel and CSV files to the database in Laravel 11 applications.

Here are the steps for creating the upload form, setting up Matwebsite/Excel, creating the route and methods to handle reading the Excel and CSV file data, and inserting it into the database:

Step 1 – Install maatwebsite/excel Package

Installing maatwebsite/excel package using the following command:

composer require maatwebsite/excel

Step 2 – Create Import Class

Create an import class name UsersImport.php file in app/Imports folder:

php artisan make:import UsersImport --model=User

Define method into it to import Excel data in database:

<?php

namespace App\Imports;

use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class UsersImport implements ToModel, WithHeadingRow
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row['name'],
'email' => $row['email'],
'password' => \Hash::make($row['password']),
]);
}
}

Step 3 – Create View for Upload Form

Create a Blade view file named import.blade.php inside the resources/views folder to allow user to choose excel or csv file for upload:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel 11 Import Excel and CSV File To Database Example Tutorial - Tutsmake.com</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.card-header h2 {
margin-bottom: 0;
}
</style>
</head>
<body>
<div class="container mt-5">
@if(session('status'))
<div class="alert alert-success">{{ session('status') }}</div>
@endif
<div class="card">
<div class="card-header">
<h2 class="float-left">Import Excel, CSV File in database using Laravel 11 - Tutsmake.com</h2>
</div>
<div class="card-body">
<form id="excel-csv-import-form" method="POST" action="{{ url('import') }}" accept-charset="utf-8" enctype="multipart/form-data">
@csrf
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input type="file" class="form-control" name="file" placeholder="Choose file">
</div>
@error('file')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
@enderror
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>

Step 4 – Define Routes

Define routes in routes/web.php file to handle import csv or excel upload requests:

use App\Http\Controllers\ExcelImportController;

Route::get('/import', [ExcelImportController::class, 'showForm']);
Route::post('/import', [ExcelImportController::class, 'import'])->name('import');

Step 5 – Create Controller File

Create a controller file to handle importing CSV or excel file logic into it:

php artisan make:controller ExcelImportController

Open app/http/controllers/ExcelCSVController.php file and add the following code into it:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Exports\UsersExport;
use App\Imports\UsersImport;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\User;
class ExcelImportController extends Controller
{
/**
* @return \Illuminate\Support\Collection
*/
public function showForm()
{
return view('import');
}

/**
* @return \Illuminate\Support\Collection
*/
public function import(Request $request)
{
$validatedData = $request->validate([
'file' => 'required',
]);
Excel::import(new UsersImport,$request->file('file'));

return redirect('import')->with('status', 'File has been imported');
}

}

Step 6 – Test Application

Run the following command to start application server:

php artisan serve

Visit the import form page (http://localhost:8000/import), select an Excel file, and click the “Import” button.

In this tutorial, you saw how to easily store CSV and Excel file data in the database using MatWebsite/Excel package in Laravel 11 applications.

Recommended Guides

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *