How to add Image Validation Rules in Laravel 11

How to add Image Validation Rules in Laravel 11

Hi Devs,

In this article, we will see how to use image validation rules in Laravel 11. As we know Laravel provide many validation rules like Dimensions of image, size of image, image type etc.

We can image types such as “jpg, png, gif, jpeg,svg” by using Laravel image validation rules. We can also set the maximum size of the image which we want to upload and also the minimum required size. Here is the step-by-step guide on how to use image validation rules in Laravel 11.

Step #01: Fresh project

If you have already a Laravel project you can use it, otherwise, you create a new one by using this command.

Composer create-project Laravel/Laravel imagevalidation

Step #02: Controller

Now we need a controller to manage views and validation rules. Run the given command to create a controller and update it with the given code.

Php artisan make:controller ImageValidationController


<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
  
class ImageValidationController extends Controller
{
    public function index(): View
    {
        return view('imageUpload');
    }
        
    public function store(Request $request): RedirectResponse
    {
        $this->validate($request, [
            'image' => [
                        'required',
                        'image',
                        'mimes:jpg,png,jpeg,gif,svg', // allowed images types
                        'dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000',
                        'max:5000' //max size 5MB
                       ],
        ]);
        
        $imageName = time().'.'.$request->image->extension();  
        $request->image->move(public_path('images'), $imageName);
        /* 
           if you want to store it in database use $imagename to store name of image
        */
        return back()->with('success', 'Image uploaded successfully.')
                     ->with('image', $imageName); 
    }
}

Step #03: Routes

Open your web.php file which is available in the Routes folder and update them with the given code.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageValidationController;

Route::controller(ImageValidationController::class)->group(function(){
    Route::get('image-upload', 'index');
    Route::post('image-upload', 'store')->name('image.store');
});

 

Step #04: Create view

Now the last step is to create a view file which will handle image selection. Create a file named imageRules.blade.php and update it with the given code.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Add image Validation Rules</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
</head>
        
<body>
<div class="container">
  
    <div class="card mt-5">
        <h3 class="card-header p-3"><i class="fa fa-star"></i> Laravel 11 Add image Validation Rules - Theskillstock.com</h3>
        <div class="card-body">

            @if (count($errors) > 0)
                <div class="alert alert-danger">
                     <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
  
            @if ($message = Session::get('success'))
                <div class="alert alert-success alert-block">
                    <button type="button" class="close" data-dismiss="alert">×</button>
                        <strong>{{ $message }}</strong>
                </div>
                <img src="images/{{ Session::get('image') }}">
            @endif
            
            <form action="{{ route('image.store') }}" method="POST" enctype="multipart/form-data">
                @csrf
        
                <div class="mb-3">
                    <label class="form-label" for="inputImage">Image:</label>
                    <input 
                        type="file" 
                        name="image" 
                        id="inputImage"
                        class="form-control @error('image') is-invalid @enderror">
        
                    @error('image')
                        <span class="text-danger">{{ $message }}</span>
                    @enderror
                </div>
         
                <div class="mb-3">
                    <button type="submit" class="btn btn-success"><i class="fa fa-save"></i>Save</button>
                </div>
             
            </form>
        </div>
    </div>
</div>
</body>
      
</html>

Now you start server to test your project.

Php artisan serve

http://localhost:8000/image-upload

Hope it will be helpful for you.

Comments

No Comment posted Yet!

Leave a Reply

OK! You can skip this field.