CRUGG's avatar
Level 1

Laravel Validation "image" returns error that uploaded file is not an image.

Hello there! I am currently trying to make a form that lets users create posts and optionally also add images to them. For Validation, I did the following:

$request->validate([
    'content' => 'required|max:3000',
    'image' => 'nullable|image|mimes:png|max:2048',
    'title' => 'required|max:500',
    'topic' => [
        'required',
        Rule::in(["topic1", "topic2",])
    ]
]);

When I try to submit the form (which does a POST to the Endpoint where the Validation is) it works as long as I don't put an image. But if I put an image, I get an error saying "The image must be an image." Does anyone know what causes this and how I could fix this? I already tried searching for people having similar problems on the Internet but wasn't able to find anything.

0 likes
8 replies
CRUGG's avatar
Level 1

Hm.... $request->image is just a string containing the filename... But how can I achieve this to actually be the file uploaded? On the website I have:

<input type="file" class="form-control" accept=".png" name="image" id="image">
CRUGG's avatar
Level 1

I already tried that but the only thing it does is tell me that it has to be a file of type PNG. After some further debugging I noticed that even when removing the Validation, it fails. $request->file('image') is apparently null. After looking at the POST Request sent via DevTools, I cannot find any file or anything. The image value that's sent is again, just a string containing the file name

Sergiu17's avatar
Sergiu17
Best Answer
Level 60

does your form include enctype="multipart/form-data"?

<form method="POST" enctype="multipart/form-data">
5 likes
CRUGG's avatar
Level 1

It didn't. And that fixed and made it pass validation. I looked at lots of Articles on File Uploads, and none of them had this in their Examples, which is quite weird. But thank you a lot. I still have some trouble with saving the file, but I will look into this. But at least if finally passes Validation. Thank you a lot!

1 like
Amanar-Marouane's avatar

@Sergiu17 ik that 4 years LOL, i have the same problem i did all what you said guys but i still have the same issue i use a reactjs interface and laravel api endpoints and the validation error got trigred every time

Sergiu17's avatar

@Amanar-Marouane remove all the validation for the image, then check what you get in your request

$request->validate([
    'image' => 'nullable'
]);


dd($request->all());

Please or to participate in this conversation.