To add validation rules in the image; Create a method in the controller and use validate(['image' => 'required|image|mimes:jpg,png]);
to validate the image before uploading it to laravel 11 project.
Here are steps to validate image before upload in laravel:
Step 1: Add routes
Define routes in web.php file to handle image upload and validation request:
use App\Http\Controllers\FrontHomeController;
Route::get('image',[FrontHomeController::class, 'image']);
Route::post('store',[FrontHomeController::class, 'store']);
Step 2: Create Blade Views
Create blade view file and image upload form in it to send image for validation on controller:
<!DOCTYPE html>
<html>
<head>
<title>Laravel Image Validation - Tutsmake.com</title>
<!-- Bootstrap 5 CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<!-- Bootstrap 5 JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-3">
<div class="card mt-5">
<div class="card-header bg-success">
<h3 class="text-white text-center"><strong>Image Validation in Laravel</strong></h3>
</div>
<div class="card-body">
@if(count($errors) > 0)
@foreach($errors->all() as $error)
<div class="alert alert-danger">{{ $error }}</div>
@endforeach
@endif
<form action="{{ url('store') }}" method="post" enctype="multipart/form-data">
@csrf
<div class="form-group">
<label><b>Please Select Image</b></label>
<input type="file" name="image" class="form-control" value="{{ old('image') }}">
</div>
<div class="form-group text-center">
<button class="btn btn-success" type="submit">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Step 3: Add Validation Rules in Controller
Edit your controller method, and add the following image validation rules in it to validate image before upload or store; something like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FrontHomeController extends Controller
{
public function image()
{
return view('image');
}
public function store(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();
}
}
Conclusion
That’s all, you have learned how to validate image mimes type, size and dimension in laravel 11.
Laravel 11 image validation example form looks like: