How to import excel CSV files into Laravel 8

How to import excel CSV files into Laravel 8

Import Excel / CSV Data into Database in Laravel

Feb 12, 2022ยท

2 min read

Import Laravel Excel

Import CSV Files into Laravel 8

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

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

For importing excel files i am using Laravel Excel.

Step 1 - Installation

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

composer require maatwebsite/excel

Next to export config file you need run command below.

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

Step 2 - Create an Import Class inside app/Imports

Create Import Class by using artisan command

php artisan make:import UsersImport --model=User

Step 3 - Update UsersImport Class

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


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

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

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

Did you find this article valuable?

Support Shani Singh by becoming a sponsor. Any amount is appreciated!