Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Image validation in Laravel 8

Image validation in Laravel 8

In this tutorial, I will give you an example of Image validation in Laravel 8, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.

We validate image and image file size before uploading to the database and server or local folder in Laravel application.

First, what we’re doing here, This is the example :

Image validation in Laravel 8

Image validation in Laravel 8

The Requirement of Image validation in Laravel

The validation process makes a valid image or file upload. we will validate the image before uploading it and also we write validation rules with customize Messages in our Controller and display it on our Blade file. Then, we will save the file name into the database.

Recommended Article: Upload multiple images in Laravel.

So, let’s start with scratch to Image upload validation

Generating Migration :

php artisan make:migration image_upload_val_examples

Migration Structure :

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateImageUploadValExamples extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('image_upload_val_examples', function (Blueprint $table) {
            $table->id();
            $table->string('product_name',25);
            $table->string('product_image',50);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('image_upload_val_examples');
    }
}

Run Migration :

php artisan:migrate
Image validation in Laravel 8

Create Model :

php artisan make:model Model/ImageUploadValExample

app\Model\ImageUploadValExample

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class ImageUploadValExample extends Model
{
    protected $table = 'image_upload_val_examples';
}

Create Controller :

php artisan make:controller ImageUploadValController

app\Http\Controllers\ImageUploadValController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Model\ImageUploadValExample;

class ImageUploadValController extends Controller
{
    public function create(){
        return view('imgval.create');
    }

    public function store(Request $request){
     #Handle File Image with Custom Messages
     $this->validate($request, [
            'product_name'=>'required',
            'product_img' => 'required|image|max:1999'
        ],

        ['product_name.required' => 'The : Product name field can not be empty value.',
          'product_img.required' => 'The : Product image field can not be empty value.',
          'product_img.max'      => 'The maximun Size of The Product Image must not exceed :max',
        ]);

          if($request->hasFile('product_img')) 
          {
            $filenameWithExt = $request->file('product_img')->getClientOriginalName();
            $filename  = pathinfo($filenameWithExt, PATHINFO_FILENAME);
            $extension = $request->file('product_img')->getClientOriginalExtension();
            $fileNameToStore = $filename.'_'.time().'.'.$extension;
            $request->product_img->move(public_path('/uploads/ProductImg'), $fileNameToStore);
          } else {
            $fileNameToStore = 'no_img';
        }
        $reqdata = new ImageUploadValExample();
        $reqdata->product_name  = $request->product_name;
        $reqdata->product_image = $fileNameToStore;
        $reqdata->save();
    }
}

Create Routes :

routes/web.php

#Image Upload Validation Routes
Route::get('/create-image-upload','ImageUploadValController@create')->name('img.create');
Route::post('/store-image-upload','ImageUploadValController@store')->name('img.store');

Create Blade File :

resources\views\imgval\create.blade.php

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Image Upload Validation | Laravel</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class="container">
         <h3>Image upload  with validation in Laravel | www.8bityard.com</h3>
         <div class="card">
            <form name="img_val" method="post" action="{{route('img.store')}}" enctype="multipart/form-data">
               @csrf
               <div class="card-header">Please fill up all the Field's.</div>
               <div class="col-sm-4 float-right">
                  @if ($errors->any())
                  @foreach ($errors->all() as $error)
                  <div class="alert alert-danger alert-dismissible p-2">
                     <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                     <strong>Error!</strong> {{$error}}.
                  </div>
                  @endforeach
                  @endif
               </div>
               <div class="card-body">
                  <div class="row">
                     <div class="col-md-6">
                        <label for="Product Name">Product Name :</label>
                        <input type="text" class="form-control" placeholder="Enter product name" name="product_name">
                     </div>
                     <div class="col-md-6">
                        <label for="Product Image">Upload Image File :</label>
                        <input type="file" class="form-control-file" name="product_img"  accept="image/*">
                     </div>
                  </div>
               </div>
               <div class="col-md-3">
                  <button type="submit" class="btn btn-block btn-info btn-sm">Save</button>
               </div>
         </div>
         </form>
      </div>
   </body>
</html>
Image validation in Laravel 8

Now, Run your application :

http://127.0.0.1:8000/create-image-upload

Output :

Image validation in Laravel 8

Image validation in Laravel 8
When not uploading an image file.

Image validation in Laravel 8
When we uploading an image file of more than 2 MB.

Note : If you want to add some advanced validation rules, you can use this validation.

$request->validate([
  'image' =>     'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048|dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000',
        ]);

In this article, we learned How to use Image validation in Laravel 8, I hope this article will help you with your Laravel application Project.

Also Read : create infinite scroll pagination in Laravel 8.