Laravel 13 Image Validation Rules: image, mimes, max and dimensions
To validate an uploaded image in Laravel 13, use the image rule with max (kilobytes) and dimensions , or the fluent File::image() builder. Add mimes if you want to allow only specific formats, then store the file under a generated name. What do you need before you start? Laravel 13 on PHP 8.3 or newer A form with enctype="multipart/form-data" and a file input named avatar What does the image rule…
Validating uploaded images in Laravel 13 involves using image rules with options like max (kilobytes) and dimensions, or the File::image() builder. To restrict file formats, add mimes rules for specific extensions. Store the file with a generated name instead of the client-provided one. Before starting, ensure you have Laravel 13 on PHP 8.3 or newer, a form with the correct enctype and file input, and the necessary Composer packages installed.
The image rule supports various image formats like jpg, jpeg, png, bmp, gif, webp, avif, heic, and heif. SVG files are rejected unless explicitly allowed. To validate an image with string rules, use the validate method with the required, image, mimes, and max rules. For example, max:2048 sets the maximum file size to 2 MB.
To limit dimensions or aspect ratio, use the dimensions rule with constraints such as min_width, max_width, min_height, max_height, width, height, and ratio. The fluent File builder provides a chainable way to apply these constraints. For example, File::image()->max(2048)->dimensions(Rule::dimensions()->maxWidth(2000)->maxHeight(2000)) validates image size and dimensions.
You can validate multiple images by validating the array and each item separately using a wildcard. For instance, photos.* validates each item in the photos array. In a form request, define the rules for the avatar field, and you can customize validation messages as needed.
When storing the uploaded file, avoid using the client-provided name. Let Laravel generate a unique name to prevent potential security risks. In the update method, use the file method to store the file in a designated directory. Finally, verify the validation works by testing with fake files using Laravel's storage facade and testing utilities.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.