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

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article