Laravel 8 How to Validate Excel Sheet Data Before Upload

Reading Time: 7 minutes
10,765 Views

Inside this article we will see the concept of Excel Sheet Data Validation before upload using laravel 8. We will use a composer package for data validation of excel sheet.

This tutorial will be very easy to understand and easy to implement. If we try to upload data in bulk then uploading by CSV, EXCEL etc will be very good choice to dump data into database. But before upload first priority should be data validation.

We will learn Laravel 8 how to validate excel sheet data before upload.

Learn More –

Let’s get started.


Laravel Installation

We will create laravel project using composer. So, please make sure your system should have composer installed. If not, may be this article will help you to Install composer in system.

Here is the command to create a laravel project-

composer create-project --prefer-dist laravel/laravel blog

To start the development server of Laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.


Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

Install maatwebsite/excel Package & Configuration

Open project into terminal and run this composer command to install package.

$ composer require maatwebsite/excel

After package installation, open app.php file from /config folder. Search for providers and aliases add these –

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

'aliases' => [
         ....
         'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],

Create Import Class

Once you will install the above package. You will see we should have a command available in artisan list i.e make:import. We will use this command to create import class.

Open terminal and run this command –

$ php artisan make:import UsersImport --model=User

It will create a file UsersImport.php file inside /app/Imports folder.

Open UsersImport.php and write this complete code into it.

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

Create Controller

Next, we need to create a controller file.

$ php artisan make:controller DataImportController

It will create a file DataImportController.php at /app/Http/Controllers folder.

Open DataImportController.php and write this complete code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Imports\UsersImport;
use Maatwebsite\Excel\Facades\Excel;

class DataImportController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        return view('user-import');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store()
    {
        Excel::import(new UsersImport, request()->file('file'));

        return back()->with('success', 'User Imported Successfully.');
    }
}

Create Route

Open web.php from /routes folder and add these route into it.

//...

use App\Http\Controllers\DataImportController;

Route::get('users-import', [DataImportController::class, 'index']);
Route::post('import', [DataImportController::class, 'store'])->name('import');

//...

Create Blade Layout File

Go to /resources/views folder and create a file with name user-import.blade.php

Open user-import.blade.php and write this complete code into it.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Laravel 8 How to validate excel sheet data</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>

<body>

    <div class="container">
        <h4>Laravel 8 How to validate excel sheet data</h4>
        <div class="panel panel-primary">
            <div class="panel-heading">Laravel 8 How to validate excel sheet data</div>
            <div class="panel-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">
                              <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">
                                <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>

Application Testing

Run this command into project terminal to start development server,

php artisan serve

URL: http://127.0.0.1:8000/users-import

Select a excel file with this pattern and upload here.

Data rows will be count from index 0 here. If suppose you don’t specify any value for Name then error will be like this 0.name required, 0.email required etc for first data row.

We hope this article helped you to learn Laravel 8 How to Validate Excel Sheet Data Before Upload Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.