Laravel 8 How to Validate Excel Sheet Data Before Upload

Share this Article
Reading Time: 7 minutes
802 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.


Installation of Laravel Application

Laravel Installation can be done in two ways.

  • Laravel Installer
  • By using composer

Laravel Installer

To install Laravel via Laravel installer, we need to install it’s installer first. We need to make use of composer for that.

$ composer global require laravel/installer

This command will install laravel installer at system. This installation is at global scope, so you type command from any directory at terminal. To verify type the given command –

$ laravel

This command will open a command palette of Laravel Installer.

To create ad install laravel project in system,

$ laravel new blog

With the name of blog a laravel project will be created at your specified path.

By using composer

Alternatively, we can also install Laravel by Composer command create-project. If your system doesn’t has Composer Installed, Learn Composer Installation Steps. Here is the complete command to create a laravel project-

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

After following these steps we can install a Laravel application into system.

To start the development server of Laravel –

$ php artisan serve

This command outputs –

Starting Laravel development server: http://127.0.0.1:8000

Assuming laravel already installed at 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

Open project to terminal and type the command 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.

Find More on Laravel 8 Articles here