How to Import Excel File in Laravel?

How to Import Excel File in Laravel

Hello Laravel Friends,

Laravel is one of the most advanced PHP frameworks for web applications development. In case you are dealing with the data processing project you may use the Excel files import to Laravel application. Data importation is typical for Laravel application developments and one type is the import of Excel files.

In this tutorial, we’ll show you how you can export data from the Excel files or import data to Laravel using Laravel Excel.

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

For this code, we must first check if the uploaded file is .xlsx or .xls. After that you can validate further with your requirements. We will make use of the following import method to process the Excel file via the import class which will be created in the next step, using the Excel::import method.

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. Adjust the method as per your Excel file’s structures 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 Laravel tutorial we learned how to import Excel file using the Laravel Excel package inside the Laravel framework. What we learned here includes installation, setting up the package, implementing the controller and an importing class, a Blade view for creating files, defining routes for all these steps, and we are ready to test the file importing process.

This feature becomes very handy in case of really large datasets or if you intend to import data from a spreadsheet in Excel into your application. You may, of course, tailor this code as needed for your project, and thus you will be armed with a very robust Excel import function in your Laravel application.

If you feel that you are stuck anywhere, you are free to reach me at the comment box or Hire Experienced Laravel Developers to help you with many different aspects of your Laravel project.

Happy Coding!

Previous Article

8 Customer Retention Strategies for Shopify Stores [2024]

Next Article

7 Best Google Shopping Apps For Shopify [2024]

Write a Comment

Leave a Comment

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

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨