Laravel provides a lot of validation rules which makes our development process faster and easier. In this post, we are going to explain a set of validation rules for Image. Let’s start with the basic one.
Image
The file under validation must be an image.
// Example: $this->validate($request, [ 'profile_image' =>'image' ]);
MIME
We can limit the MIME types of uploaded image using mimes
in validation rules. So, the file under validation must have a MIME type corresponding to one of the listed extensions. A image with only jpeg(jpg) or png extensions are allowed with the example below.
// Example: $this->validate($request, [ 'profile_image' =>'mimes:jpeg,png' ]);
Size
The field under validation must have a size matching the given value. This works for both string and file types. For string data, the value corresponds to the number of characters. For numeric data, the value corresponds to a given integer value. For an array, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes.
// Example: $this->validate($request, [ 'profile_image' =>'image|size:1024' ]);
Dimensions
This dimensions
validation rule is quite interesting. We can pass a number of parameters with it. The set of parameters that can be passed are as below:
min_width
: Images should not be narrower than this pixel widthmax_width
: Images should not be wider than this pixel widthmin_height
: Images should not be shorter than this pixel heightmax_height
: Images should not be taller than this pixel heightwidth
: Images should be exactly this pixel widthheight
: Images should be exactly this pixel heightratio
: Images should be exactly this ratio (width/height, expressed as “width/height”)
// Example $this->validate($request, [ 'profile_image' => 'dimensions:min_width=250,min_height=250' ]); // or... $this->validate($request, [ 'profile_image' => 'dimensions:min_width=250,max_width=250' ]); // or... $this->validate($request, [ 'profile_image' => 'dimensions:width=250,height=250' ]); // or... // Ensures that the width of the image is 1.5x the height $this->validate($request, [ 'profile_image' => 'dimensions:ratio=3/2' ]);
Now what?
You can implement these validation rules for uploading multiple images in laravel 5. On the other hand, you can also create an image gallery system following these articles.
This is all for validating image. Hope you found this article interesting. If you have any queries, don’t forget to drop a comment below. Happy Coding.