DEV Community

Cover image for How to import excel CSV file into Laravel
shani singh
shani singh

Posted on

How to import excel CSV file into Laravel

Import Laravel Excel

Import Excel 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

In case of any query related to LARAVEL.
Reach Out To me.
Twitter
Instagram

Top comments (5)

Collapse
 
abdelqaouinabil profile image
AbdelqaouiNabil

what about gettiong also images from the cvs file

Collapse
 
shanisingh03 profile image
shani singh

You can put Image Path and Get that by File get Method of PHP.

Collapse
 
farirai123 profile image
Farirai Masocha

having problems uploading csv data to mysql database using laravel orchid