Laravel 12 Image Validation Rules: Complete Guide with Example

Laravel 12 Image Validation Rules Complete Guide with Example

Laravel 12 provides several built-in validation rules for validating image and photo uploads. Commonly used image validation rules include image, mimes, max, min, and dimensions.

Using Laravel’s default validation rules, you can:

  • Restrict allowed image file types such as jpg, jpeg, png, gif, svg
  • Set a maximum or minimum file size using the max and min rules
  • Control image width and height using the dimensions rule

By combining these validation rules, you can easily ensure that only valid images are uploaded to your application.

Hire laravel Developer

Steps for Laravel 12 Validation Rules for Image and Photo

Step 1: Install Laravel 12

If you have not created the Laravel app, then you may execute the following command:

composer create-project laravel/laravel example-app

Step 2: Create Controller

In this step, we will create a new ImageController; in this file, we will add two methods, index() and store(), for render view and storing image logic, respectively.

Let’s create ImageController with the following command:

php artisan make:controller ImageController

Next, let’s update the following code in the Controller File.

app/Http/Controllers/ImageController.php

<?php

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

class ImageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function index(): View
    {
        return view('imageUpload');
    } 

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function store(Request $request): RedirectResponse
    {
        $this->validate($request, [
            'image' => [
                        'required',
                        'image',
                        'mimes:jpg,png,jpeg,gif,svg',
                        'dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000',
                        'max:2048'
                       ],
        ]); 
       
        $imageName = time().'.'.$request->image->extension();           
        $request->image->move(public_path('images'), $imageName); 
     
        /* 
            Write Code Here for
            Store $imageName name in DATABASE from HERE 
        */ 
       
        return back()->with('success', 'You have successfully upload image.')
                     ->with('image', $imageName); 
    }
}

Step 3: Create Routes

Furthermore, open routes/web.php file and add the routes to manage GET and POST requests for render view and storing the image logic.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageController;

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

Step 4: Create Blade File

At the last step, we need to create the imageUpload.blade.php file, and in this file, we will create a form with a file input button. So copy below and put in that file.

resources/views/imageUpload.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 12 Image Validation Rules: Complete Guide with Examples</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 12 Image Validation Rules: Complete Guide with Examples</h3>
        <div class="card-body">
            @if (count($errors) > 0)
                <div class="alert alert-danger">
                    <strong>Whoops!</strong> There were some problems with your input.<br><br>
                    <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> Upload</button>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>

Run Laravel App

All the required steps have been completed. Now, type the command below and press Enter to run the Laravel app.

php artisan serve

Now, go to your web browser, type the given URL, and view the app output.

http://localhost:8000/image-upload 

Conclusion

Laravel 12 offers a robust and developer-friendly approach to image validation. By using built-in rules such as image, mimes, max, and dimensions, you can ensure secure and optimized image uploads across your application.

Laravel Development Services

FAQ

1. What image formats are supported by Laravel’s image rule?

Laravel supports jpeg, png, jpg, gif, bmp, svg, and webp by default.

2. What is the difference between image and mimes rules?

  • An image validates the file as an actual image
  • mimes restricts file extensions

Best practice is to use both together.

3. Is image validation secure in Laravel?

Yes, Laravel validates both file type and MIME type, making it highly secure when used correctly.

Previous Article

Choosing the Right Server for Your Online Project

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨