I’m working with Laravel 5.8 and I have made this Controller method for creating some records inside the DB.
public function doTheUpload(Request $request)
{
try{
$request->validate([
'video' => 'nullable|mimes:mp4',
'video_thumb' => 'required|mimes:jpg,png,jpeg',
'video_name' => 'required',
'video_desc' => 'nullable',
'available_download' => 'nullable',
],[
'video.mimes' => 'video file format is not valid',
'video_thumb.required' => 'uploading video thumbnail is required',
'video_name.required' => 'you must enter name of video',
'video_thumb.mimes' => 'image thumbnail file format is not valid',
]);
// Do the upload process
}catch(Exception $e){
dd($e);
}
}
But this will not working and return this error:
The given data was invalid.
This is basically because of the form validation requests and when I remove those validations from the method, it will work absolutely fine.
So what is wrong with those form request validation that returns this error?
If you know, please let me know… I would really really appreciate any idea or suggestion from you guys.
Thanks.
2
Answers
You must specify exactly what you are validating:
An example from my codes:
When you use Laravel’s validation, you should let Laravel handle the errors, because when a rule fails, Laravel automatically throws an exception.
So the first advise is no to use a try-catch block in your validation routine.
As Laravel docs states:
In addition, I suggest you not to use validation in the controllers because according to good practices, it is recommended to create separate formRequest for validation, so you should slightly modify you controller to include validator class:
Now you have to create a form request, maybe using
php artisan make:request UploadVideoRequest
This command will create a form request class under
app/Http/Requests
, and you should fill it as:By using this approach Laravel is validating user input and managing any error via Exceptions.
Regards.