Laravel

How to Import Excel File in Laravel?

Hello Laravel Friends,

Laravel is a powerful PHP framework that simplifies web application development. If your project involves handling data, you might need to import data from Excel files into your Laravel application. Importing Excel files into a Laravel application can be a common task, especially when dealing with data imports from various sources.

In this tutorial, I’ll guide you through the process of importing Excel files in Laravel using the popular Laravel Excel package.

Prerequisites to Import Excel File in Laravel:

Before we dive into the tutorial, make sure you have the following prerequisites:

  • A Laravel project set up and running.
  • Basic knowledge of Laravel’s Eloquent ORM and Blade templating engine.
  • Composer installed on your system.

Steps to Import Excel File in Laravel:

Step 1: Install Laravel Excel

To get started, you’ll need to install the Laravel Excel package. Open your terminal and navigate to your Laravel project’s root directory. Then, run the following command:

composer require maatwebsite/excel

This command will download and install the Laravel Excel package and its dependencies.

Step 2: Configure the Package

After installation, you need to configure the Laravel Excel package. Open the config/app.php file and add the following service provider and alias to the providers and aliases arrays, respectively:

// config/app.php

'providers' => [
    // ...
    Maatwebsite\Excel\ExcelServiceProvider::class,
],

'aliases' => [
    // ...
    'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],

Next, publish the package configuration file by running the following command:

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"

This command will create a config/excel.php file where you can customize your Excel import settings.

Step 3: Create a Controller

Now, let’s create a controller to handle the Excel file import. Run the following command to generate a new controller:

php artisan make:controller ExcelImportController

This command will create a file named ExcelImportController.php in the app/Http/Controllers directory.

Step 4: Define the Import Logic

Open the ExcelImportController.php file and define the import logic in a method. For example, let’s create a method named import:

// app/Http/Controllers/ExcelImportController.php

use Excel;

class ExcelImportController extends Controller
{
    public function import(Request $request)
    {
        // Validate the uploaded file
        $request->validate([
            'file' => 'required|mimes:xlsx,xls',
        ]);

        // Get the uploaded file
        $file = $request->file('file');

        // Process the Excel file
        Excel::import(new YourImportClass, $file);

        return redirect()->back()->with('success', 'Excel file imported successfully!');
    }
}

In this code, we first validate that the uploaded file is of type .xlsx or .xls. You can adjust the validation rules according to your needs. Next, we use the Excel::import method to process the Excel file using an import class that we’ll create in the next step.

Step 5: Create an Import Class

You need to create an import class that specifies how the data from the Excel file should be imported. Run the following command to generate an import class:

php artisan make:import YourImportClass

This command will create a file in the app/Imports directory. Open this file and define the import logic. Here’s an example of how it might look:

// app/Imports/YourImportClass.php

namespace App\Imports;

use Maatwebsite\Excel\Concerns\ToModel;

class YourImportClass implements ToModel
{
    public function model(array $row)
    {
        // Define how to create a model from the Excel row data
        return new YourModel([
            'column1' => $row[0],
            'column2' => $row[1],
            // Add more columns as needed
        ]);
    }
}

In this code, the model method specifies how to create a model from the data in each row of the Excel file. You should adjust this method to match your Excel file’s structure and your Laravel model.

Step 6: Create a Blade View

Now, create a Blade view that allows users to upload the Excel file. Here’s a simple example:

<!-- resources/views/excel-import.blade.php -->

@extends('layouts.app')

@section('content')
<div class="container">
    @if(session('success'))
        <div class="alert alert-success">
            {{ session('success') }}
        </div>
    @endif

    <form action="{{ route('import.excel') }}" method="POST" enctype="multipart/form-data">
        @csrf
        <div class="form-group">
            <label for="file">Choose Excel File</label>
            <input type="file" name="file" id="file" class="form-control">
        </div>
        <button type="submit" class="btn btn-primary">Import</button>
    </form>
</div>
@endsection

This Blade view includes a form with a file input field for uploading Excel files. It also displays a success message if the import is successful.

Step 7: Create a Route

In your web.php file (located in the routes directory), define a route for the Excel import view and the import action:

// routes/web.php

Route::get('/import-excel', 'ExcelImportController@index')->name('import.excel');
Route::post('/import-excel', 'ExcelImportController@import');

Step 8: Test the Excel Import

With everything set up, you can now test your Excel import feature. Start your Laravel development server by running:

php artisan serve

Visit the Excel import page in your browser, usually at http://localhost:8000/import-excel. Upload an Excel file, and if everything is configured correctly, the data should be imported into your database.

Conclusion:

In this tutorial, we’ve demonstrated how to import Excel files in Laravel using the Laravel Excel package. You learned how to install and configure the package, create a controller and an import class, set up a Blade view for file uploads, define routes, and test the import process.

This feature can be immensely valuable when dealing with large datasets or when migrating data from Excel spreadsheets into your Laravel application. Feel free to customize the code to fit your specific project requirements, and you’ll have a robust Excel import functionality integrated into your Laravel application.

In case you are stuck anywhere, connect with me through the comment box or Hire Experienced Laravel Developers to help you with various aspects of your Laravel project.

Happy Coding!

Click to rate this post!
[Total: 18 Average: 4.6]
Bharat Desai

Bharat Desai is a Co-Founder at MageComp. He is an Adobe Magento Certified Frontend Developer 🏅 with having 8+ Years of experience and has developed 150+ Magento 2 Products with MageComp. He has an unquenchable thirst to learn new things. On off days you can find him playing the game of Chess ♟️ or Cricket 🏏.

Recent Posts

Magento 2: How To Call JS on the Checkout Page?

Hello Magento mates, Today we will learn to add a call JS on the checkout…

2 days ago

Boost Your SEM Game: Unveiling the Top 10 Tools for Marketers in 2024

Business survival in today’s digital world has become extremely difficult. Using traditional marketing techniques is…

3 days ago

Five Essential Payroll Compliance Tips for eCommerce Startups

Are you setting up a payroll system for your eCommerce startup? Ensuring compliance with myriad…

4 days ago

Optimizing Laravel Blade: Unlocking Advanced Fetcher Techniques

In the expansive universe of Laravel development, Blade serves as the stellar templating engine, propelling…

4 days ago

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

6 days ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

1 week ago