Laravel provides several different approaches to validate your application's incoming data. By default, Laravel's base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules.
Laravel has a number of Available Validation rules to work with. But we’ll be going through the ones helpful in validating images specifically.
Image Rule
This one is probably the most straight forward one. It would validate that the file uploaded must be an image i.e. jpeg, png,gif etc
public function rules()
{
return [
'img' => 'image',
];
}
Mimes Rule
With Mimes, we can limit the extensions for the uploaded image likeso
public function rules()
{
return [
'img' => 'mimes:jpeg,png',
];
}
In this case, It will only accept jpeg and png type image.
Read more about the mime types
Size Rule
This rule validates the uploaded file size in kilobytes
public function rules()
{
return [
'img' => 'image|size:2048', // 2 MB
];
}
Dimensions Rule
With the dimensions rule, you can specify the min/max, width/height of the uploaded image.
public function rules()
{
return [
'img' => 'dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000',
];
}
You can also specify a ratio of an image likeso,
public function rules()
{
return [
'img' => 'dimensions:ratio=3/2',
];
}
3/2 which would cover 600×400 and 300×200 etc
Moreover, we can even combine width, height ratio by using Rule facade.
public function rules()
{
return [
'avatar' => [
'required',
Rule::dimensions()->maxWidth(1000)->ratio(3/2),
],
];
}
Try out these rules for your next image uploads.