How to validate image in Laravel

I am trying laravel image validation for the following field-

<label class="btn btn-success">
    <input name="image" type="file"/>Add Image</label>
    @if ($errors->has('image'))
       <span class="alert alert-danger">
          {{ $errors->first('image') }}
       </span>
    @endif

And my validation rule is written like this-

$request->validate([
  'image'=> 'mimes:jpeg,jpg,png,gif|max:1000',
]);

But no matter what whether I give a valid image as input or not my validation rule gives me this error-

The image must be a file of type: jpeg, jpg, png, gif.

You can consider me beginner in laravel and I cant really find out what I am doing wrong here. Can anyone help?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Try this set of rules for your image input field:

'image' => 'nullable|image|mimes:jpeg,jpg,png,gif',

This will:

  • make the field nullable, so you can send it as null
  • image to validate the filetype (see doc)
  • mimes:jpeg,jpg,png,gif that will check for specific file mime type (doc) (also check mimetypes)

You can even check image idmension.
Take a look at available rules, custom validation rules and the intervention image package.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x