Laravel Tutorials

Image Dimension Validation with Laravel's dimensions Rule

Published
Image Dimension Validation with Laravel's dimensions Rule image

Laravel offers powerful image validation capabilities through the dimensions rule, providing fine-grained control over image size and proportions for your application's media uploads.

The basic implementation demonstrates the rule's flexibility:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
 
// Basic validation
$validator = Validator::make($request->all(), [
'profile_photo' => [
'required',
Rule::dimensions()
->minWidth(400)
->minHeight(400)
->maxWidth(2000)
->maxHeight(2000)
]
]);

Here's how to implement a comprehensive image validation strategy in a media management system:

class MediaController extends Controller
{
public function upload(Request $request)
{
$imageType = $request->input('type', 'standard');
 
$rules = [
'image' => array_merge(
['required', 'image', 'max:10240'], // 10MB max
$this->getDimensionRules($imageType)
)
];
 
$request->validate($rules);
 
// Process and store the validated image
$path = $request->file('image')->store('media/' . $imageType);
 
return response()->json([
'success' => true,
'path' => $path
]);
}
 
protected function getDimensionRules(string $type): array
{
return match($type) {
'thumbnail' => [
Rule::dimensions()
->width(300)
->height(300)
],
'hero' => [
Rule::dimensions()
->minWidth(1200)
->minHeight(600)
->maxHeight(800)
->ratio(2)
],
'gallery' => [
Rule::dimensions()
->minWidth(800)
->minHeight(600)
->maxWidth(3000)
->maxHeight(2000)
],
default => [
Rule::dimensions()
->minWidth(400)
->minHeight(400)
]
};
}
}

The dimensions rule ensures optimal image quality throughout your application while preventing storage and bandwidth issues from improperly sized uploads.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Image Dominant Color and HEIC Support in Laravel 13.24 image

Image Dominant Color and HEIC Support in Laravel 13.24

Read article
Official Laravel Zed Extension: LSP for PHP & Blade image

Official Laravel Zed Extension: LSP for PHP & Blade

Read article
Laravel Head: Manage Meta Tags, Open Graph, and JSON-LD image

Laravel Head: Manage Meta Tags, Open Graph, and JSON-LD

Read article
PhpStorm 2026.2 Released image

PhpStorm 2026.2 Released

Read article
Laravel Doctor: Diagnose Your App With One Artisan Command image

Laravel Doctor: Diagnose Your App With One Artisan Command

Read article
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article