Laravel 11 Import Excel and CSV File Tutorial

Laravel 11 Import Excel and CSV File Tutorial
In this tutorial, we will walk you through the process of importing Excel and CSV files in Laravel 11 using the Maatwebsite/Excel package. This package is a popular choice among Laravel developers for its simplicity and efficiency in handling data import and export.

Installing Maatwebsite/Excel Package

To begin, you need to install the Maatwebsite/Excel package using the following Composer command:
composer require maatwebsite/excel

Creating an Import Class

Next, create an import class named UsersImport.php in the app/Imports directory using the Artisan command:
php artisan make:import UsersImport --model=User
In the UsersImport class, define a method to import Excel data into the database:
<?php

namespace App\Imports;

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

class UsersImport implements ToModel, WithHeadingRow
{
    public function model(array $row)
    {
        return new User(&#91;
            'name'     => $row['name'],
            'email'    => $row['email'],
            'password' => \Hash::make($row['password']),
        ]);
    }
}

Creating the Upload Form View

Create a Blade view file named import.blade.php inside the resources/views folder to allow users to upload Excel or CSV files:

 
<!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 Tutorial - Development Query</title>
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/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 - Development Query</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>

Defining Routes

Define the necessary routes in the routes/web.php file to handle the import requests:

 
use App\Http\Controllers\ExcelImportController;

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

Creating the Controller

Create a controller to handle the logic for importing the CSV or Excel file:

php artisan make:controller ExcelImportController

Open the app/Http/Controllers/ExcelImportController.php file and add the following code:

 
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Imports\UsersImport;
use Maatwebsite\Excel\Facades\Excel;

class ExcelImportController extends Controller
{
    public function showForm()
    {
       return view('import');
    }

    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');
    }
}

Testing the Application

To test the application, start the development server using the following Artisan command:

 
php artisan serve

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

Conclusion

In this tutorial, we demonstrated how to import data from Excel and CSV files into a Laravel 11 application using the Maatwebsite/Excel package. This process simplifies data management and enhances the functionality of Laravel applications.

For more information on the Maatwebsite/Excel package, visit the official documentation.

Writing by Kanha Jatthap

Development Query

This article is optimized using Content AI to ensure maximum effectiveness and relevance.

Share the Post:

Table of Contents

Join Our Newsletter