How to Validate Excel Sheet Data in Laravel?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now here i will show you How to Validate Excel Sheet Data in Laravel? So, let’s start and see an article for how to validate excel sheet data in laravel application. Here I’m going to tell you about laravel maatwebsite excel import data validation. From here you will learn about laravel maatwebsite validation example. So here i will help you and also i will give you an example of laravel validate excel data.

So Let’s see the bellow example about how to validate for excel data in laravel application.

When we are need to work with excel or csv file for import and export then all of us always prefer to use maatwebsite composer package. But when we need to validate the excel sheet data by using maatwebsite package and you don’t know then i hope you are right place . Here i will give you a very simple an example how to done that.

We can also use this same example with any version of laravel such as laravel 6, laravel 7 and laravel 8 version

Step 1: Install maatwebsite/excel Package

For this example we need to install the maatwebsite/excel package via the Composer package manager, so need to open your terminal and fire the bellow command:

composer require maatwebsite/excel

Now need to open config/app.php file and add the service provider and aliase.

config/app.php

'providers' => [
	....
	Maatwebsite\Excel\ExcelServiceProvider::class,
],

'aliases' => [
	....
	'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],
Step 2: Add Routes

Now in this step, we have to create a new route for export file. So just open your “routes/web.php” file and add the following route.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
    
use App\Http\Controllers\UserImportController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('import', [UserImportController::class, 'index']);
Route::post('save-import', [UserImportController::class, 'store'])->name('import');

Step 3: Create Import Class

In maatwebsite 3 version provide us a way to built an import class and also we have to use in controller. So it will be great way to create the new Import class. So we just need to run the following command and change the following code on that file:

php artisan make:import UsersImport --model=User

app/Imports/UsersImport.php

<?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']),
            ]);
        }
    }
  
}

Step 4: Create Controller

Then now in this step, now we need to create a new controller as name UserImportController in location “app/Http/Controllers/UserImportController.php”. By using this controller will manage the all index and store method, sojust put bellow code in your controller file:

app/Http/Controllers/UserImportController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Imports\UsersImport;
use Maatwebsite\Excel\Facades\Excel;
  
class UserImportController extends Controller
{
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
       return view('import');
    }
     
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store() 
    {
        Excel::import(new UsersImport,request()->file('file'));
             
        return back()->with('success', 'User Imported Successfully.');
    }
}

Step 5: Create Blade File

Now we are in Last step, so let’s create a blade file as name import.blade.php in location (resources/views/import.blade.php) for your layout and then we need to write design code here and put following code:

resources/views/import.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to validate excel sheet data in Laravel - Codingspoint.com</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
</head>
<body>
     
<div class="container">
    <div class="card bg-light mt-3">
  
        <div class="card-header">
            How to validate excel sheet data in Laravel - CodingsPoint.com
        </div>
        <div class="card-body">
            <form action="{{ route('import') }}" method="POST" enctype="multipart/form-data">
                @csrf
  
                @if (count($errors) > 0)
                <div class="row">
                    <div class="col-md-8 col-md-offset-1">
                      <div class="alert alert-danger alert-dismissible">
                          <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                          <h4><i class="icon fa fa-ban"></i> Error!</h4>
                          @foreach($errors->all() as $error)
                          {{ $error }} <br>
                          @endforeach      
                      </div>
                    </div>
                </div>
                @endif
  
                @if (Session::has('success'))
                    <div class="row">
                      <div class="col-md-8 col-md-offset-1">
                        <div class="alert alert-success alert-dismissible">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                            <h5>{!! Session::get('success') !!}</h5>   
                        </div>
                      </div>
                    </div>
                @endif
  
                <input type="file" name="file" class="form-control">
                <br>
                <button class="btn btn-success">Submit</button>
            </form>
        </div>
    </div>
</div>
     
</body>
</html>

So now we can check it on our laravel 8 application.

Now finally we are ready to run our this example. So just run the bellow command for quick run:

php artisan serve

Now we need to open the bellow URL on our browser:

localhost:8000/import

I hope it is working and you can learn.

Read Also :Laravel Join with Subquery in Query Builder Example

Thanks for read. I hope it help you. For more you can follow us on facebook.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →