user12520063
user12520063

Reputation:

Laravel Image validation only accepting .png files

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>

Upvotes: 3

Views: 2330

Answers (3)

Lewis
Lewis

Reputation: 3415

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.

Upvotes: 2

sajjad
sajjad

Reputation: 487

public function store() {

        $data = request()->validate([
            'caption' => 'required',
            'image' => 'required|file|mimes:jpeg,jpg,png'
        ]);

        Post::create($data); 
 }

Upvotes: 2

Wassim Al Ahmad
Wassim Al Ahmad

Reputation: 1094

"image"=>'image | required | mimes:jpeg,png,jpg,gif,svg | max:2048',

in your cause you can choose mimes: png

Upvotes: 0

Related Questions