Laravel

Image Validation in Laravel

Before uploading images on server it must be validate to sanitize the user input . It could be malicious attack if we didn’t validate image before uploading. Improper validation of image could lead security vulnerability. So we need to validate image before saving them on the server to reduce the vulnerability.

Here we will learn how to validate image and image file mime type, size, and dimension in laravel.

This tutorial will help us to validate image and image file mime type like like jpeg, png, bmp, gif, svg, or webp before uploading to database and server folder in laravel app.

Steps To Implement Image Validation.

Follow the following steps and validate image mime type, size, and dimension before uploading to database and server folder in laravel app:

Step 1: Add routes.

Add below routes into your web.php file. So go to routes folder and open web.php file and add the below code into your web.php file.


Route::get('image','ImageController@index');
Route::post('validateimage','ImageController@validateImage');

Step 2: Add methods on Controller.
<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class ImageController extends Controller
{
        public function index(){
             return view('image');
      }
    public function validateImage(Request $request){
             $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',
        ]);
        return redirect()->back(); 
    }
}

Step 3: Create Blade Views.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Image Validation In Laravel</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">  
</head>
<body>

<h3 class="text-success" align="center">Image Validation In Laravel</h3><br>
<div class="container">
    
  <div class="panel-group">
            @if(count($errors) > 0)                    
                        <div class="alert alert-danger">{{ $errors->first() }}</div>                   
             @endif
    <div class="panel panel-primary">
     <div class="panel-heading">Image Validation In Laravel</div>
            <form action="{{ url('validateimage') }}" method="post" enctype="multipart/form-data">   
            @csrf      
                <div class="panel-body">                 
                    <div class="form-group">
                        <label class="control-label col-sm-2">Select Image:</label>
                        <div class="col-sm-5">
                          <input type="file"  name="image">
                        </div>
                    </div>
                  <br><br>
                    <button class="btn btn-success" type="submit" style='margin-left:20%'>Upload Image</button>
            </div>
        </form>
      </div>
    </div>
</div>

Related Articles

Leave a Reply

Back to top button