Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Image validation only accepting .png files

Tags:

php

laravel

I have added a form added image file upload and validated it, the file upload accepting only .png file. When I choose jpg,jpeg or other formats throws error message field must be an image.

Laravel version Version 5.8.38

My controller Method

 public function store() {

        $data = request()->validate([
            'caption' => 'required',
            'image' => 'required | image'
        ]);

        Post::create($data); 
 }

My View

<form action="/p" enctype="multipart/form-data" method="POST">
@csrf
<div class="row">
<label for="image" class="col-md-4 col-form-label">Post Image</label>
<input type="file" class="form-control-file" id="image" name="image">

@error('image')
<strong style="color: #e3342f;font-size:80%">{{ $message }}</strong>
@enderror
</div>
</form>

1 Answers

It's a bug. This happens because the list of valid mimes specified by Laravel only includes "jpeg" but the mime guesser guesses the file type as "jpg". Since the image validation just appears to be a shorthand for validating the mime types, you can specify these yourself and add "jpeg". The following is functionality equivalent to the image validator but without the bug:

mimes:jpeg,jpg,png,gif,bmp,svg

It's important to leave out the image requirement. No need to specify file either since that's done by the mime validation.

like image 70
Lewis Avatar answered Oct 26 '25 07:10

Lewis