Laravel version: 8.82.0
I am uploading an image with inertiajs by making a post request with form.post
method. An image data is received in controller as depicted in an image below:
My simplified controller:
public function store(){
Request()->validate([
'thumbnail' => 'required|mimes:png,jpeg,jpg|max:2048'
// Also tried, still fails.
// 'thumbnail' => 'required|image|mimes:png,jpeg,jpg|max:2048'
]);
return Redirect::route('showcases.index');
}
Upon ariving header content-type is application/json
, I tried changing it to multipart/form-data
but to no avail, image validation still fails.
The error I get is: The thumbnail must be a file of type: png, jpeg, jpg
CodePudding user response:
you are trying to validate a base64 string instead of a file.
in the string format laravel validation cant validate the mime type.
so you may try to extend the validation rules and try a better way.
Inside the AppServiceProvider
put the custom validation(there are many other cleaner ways)
public function boot()
{
Validator::extend('image64', function ($attribute, $value, $parameters, $validator) {
$type = explode('/', explode(':', substr($value, 0, strpos($value, ';')))[1])[1];
if (in_array($type, $parameters)) {
return true;
}
return false;
});
Validator::replacer('image64', function($message, $attribute, $rule, $parameters) {
return str_replace(':values',join(",",$parameters),$message);
});
}
now you can do :
'thumbnail' => 'required|image64:jpeg,jpg,png'