DEV Community

Cover image for Import Excel File into Laravel 8
TechTool India
TechTool India

Posted on

Import Excel File into Laravel 8

Import Laravel Excel

Import CSV Files into Laravel 8

Today I am Going To Explain you about how you can import Excel / CSV Files into Laravel.

I am going to use Tech-Admin Panel for this.

For importing excel file i am using Laravel Excel.

Step 1 - Installation

To Install the Laravel Excel Package via composer run command below.

composer require maatwebsite/excel
Enter fullscreen mode Exit fullscreen mode

Next to export config file you need run command below.

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
Enter fullscreen mode Exit fullscreen mode

Step 2 - Create an Import Class inside app/Imports

Create Import Class by using artisan command

php artisan make:import UsersImport --model=User
Enter fullscreen mode Exit fullscreen mode

Step 3 - Update UsersImport Class

In order use CSV/Excel Files with heading we have to implement WithHeadingRow, UsersImport Class will look like.

<?php

namespace App\Imports;

use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
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([
            "first_name" => $row['first_name'],
            "last_name" => $row['last_name'],
            "email" => $row['email'],
            "mobile_number" => $row['mobile_number'],
            "role_id" => 2, // User Type User
            "status" => 1,
            "password" => Hash::make('password')
        ]);
    }
}

Enter fullscreen mode Exit fullscreen mode

Step 4 - Handle Uploaded Excel/CSV File

public function uploadUsers(Request $request)
{
        Excel::import(new UsersImport, $request->file);

        return redirect()->route('users.index')->with('success', 'User Imported Successfully');
}
Enter fullscreen mode Exit fullscreen mode

You can watch the explanation video for more clarity.

In Next part i will explain about Export Users.

Thank You for Reading!

Reach Out To me.
Twitter
Instagram
YouTube

Top comments (0)