Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Import Excel and CSV File to Database Example

Last Updated on April 19, 2024 by

In Laravel 11, importing CSV or Excel files means reading data from these files and inserting them into the database.

Let’s start by creating a form that allows users to select and upload CSV or Excel files and implement logic in controller to handle file uploads with Maatwebsite\Excel:

Step 1 – Install Laravel Excel Package

Install Laravel Excel package to handle Excel and csv file imports:

composer require maatwebsite/excel

Step 2 – Create Import Class

Run the following artisan command to create import class:

php artisan make:import ImportExcel

Add the import class field in it:

<?php

namespace App\Imports;

use App\Models\YourModel;
use Maatwebsite\Excel\Concerns\ToModel;

class ImportExcel implements ToModel
{
    public function model(array $row)
    {
        return new YourModel([
            'column1' => $row[0],
            'column2' => $row[1],
            // Map other columns accordingly
        ]);
    }
}

Step 3 – Create Import Form

Create form in resource/views/import_form.blade.php to import excel and csv file:

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

    <title>Laravel 11 Import csv and excel file - ITCODSTUFF.COM</title>
</head>
<body>
    @if (Session::has('success'))
        <div class="alert alert-success">{{ Session::get('success') }}</div>
    @endif

    <div class="container mt-5">
        <form action="{{ route('upload.file') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="mb-3">
                <label for="file" class="form-label">Choose File</label>
                <input type="file" class="form-control" id="file" name="file" accept=".csv, .xlsx">
            </div>
            <button type="submit" class="btn btn-primary">Upload</button>
        </form>
    </div>
</body>
</html>

Step 4 – Add Routes

Add routes in web.php file to handle import requests:

use App\Http\Controllers\FileController;

Route::get('/upload', [FileController::class, 'showImportForm']);
Route::post('/upload', [FileController::class, 'uploadFile'])->name('upload.file');

Step 5 – Create Controller File

Create a controller file using the following artisan command:

php artisan make:controller FileController

In FileController, implement methods to handle excel and csv file upload and import.

<?php

namespace App\Http\Controllers;

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

class FileController extends Controller
{
    public function showImportForm()
    {
        return view('import_form');
    }

    public function uploadFile(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:csv,xlsx|max:2048',
        ]);

        if ($request->file('file')->getClientOriginalExtension() == 'csv') {
            // Handle CSV file
            $data = array_map('str_getcsv', file($request->file('file')));
            // Process $data as needed
        } else {
            // Handle Excel file
            Excel::import(new ImportExcel, $request->file('file'));
        }

        return redirect()->back()->with('success', 'File imported successfully');
    }
}

Step 6 – Test Application

Start the Laravel development server:

php artisan serve

Start browser and navigate to http://127.0.0.1:8000/upload to upload CSV or Excel files.

Leave a Comment