Validate Excel Data Before Import Example in Laravel

Hello Artisan

In this example i will show you how to validate excel sheet data in laravel. I’m going to show you excel sheet data validation about laravel maatwebsite excel import validation. So you will learn laravel maatwebsite validation example.

I will help you to let you know the way of laravel validate excel data. Let's see bellow example that how to validate for excel data in laravel. When we are going to work excel or csv import and export then we always use maatwebsite composer package for laravel application.

In Laravel application, how we can validate excel sheet data, this is our goal in this tutorial. Let's see the example. 

 

Step 1: Create Import File

Let assume you have installed maatwebsite excel package in your laravel application. So run this command.

php artisan make:import UsersImport --model=User

 

Now to validate excel data, just update the below file like that

app/Imports/UsersImport.php

namespace App\Imports;
  
use App\Models\User;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Facades\Validator;
  
class UsersImport implements ToCollection, WithHeadingRow
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function collection(Collection $rows)
    {
         Validator::make($rows->toArray(), [
             '*.name' => 'required',
             '*.email' => 'required',
             '*.password' => 'required',
         ])->validate();
  
        foreach ($rows as $row) {
            User::create([
                'name' => $row['name'],
                'email' => $row['email'],
                'password' => bcrypt($row['password']),
            ]);
        }
    }
  
}

 

After doing that just use in your controller

public function store() 
{
  Excel::import(new UsersImport,request()->file('file'));        
  return back()->with('success', 'User Imported Successfully.');
}

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js