MalcolmInTheCenter
MalcolmInTheCenter

Reputation: 1605

Laravel 5.4: How do I validate an image size?

I have a form where a user can submit an image. I don't want to store it on my server in case it's a virus but instead store it to Amazon S3.

My issue is that I need to validate if the image is less than a specific dimension. How can I do that in Laravel 5.4?

My controller

 $validator = \Validator::make($request->all(),[
    "logo"      => "dimensions:max_width:300,max_height:200",
 ]);

 if($validator->fails()){
    return \Redirect::back()->withInput()->withErrors( $validator );
 }

The validation fails and redirects back with "The logo has invalid image dimensions." eventhough the image i'm uploading is 100x100. What's the correct way to validate or what are alternate solutions without having to save the file?

Upvotes: 13

Views: 25581

Answers (2)

Gass
Gass

Reputation: 9344

Here is a validation example for:

  • Image formats
  • Max file size
  • Dimensions
$request->validate([
     'avatar' => ['image','mimes:jpg,png,jpeg,gif','max:200','dimensions:min_width=100,min_height=100,max_width500,max_height=500'],
]);

max:200 (200kb max size limit)

Upvotes: 2

TalESid
TalESid

Reputation: 2514

use equals sign (=) rather than colon (:) with max_width & max_height :

"logo"  => "dimensions:max_width=300,max_height=200",

Image dimension validation rules in Laravel


If it doesn't solve, make sure that your form has enctype="multipart/form-data" (as mentioned in comment by @F.Igor):

<form method="POST" enctype="multipart/form-data">
    <input type="file" name="logo">
    <input type="submit">
</form>

If you already using this, then check (before validation) whether you are getting image with your request and with what name:

dd($request->all())

Upvotes: 23

Related Questions