Identify issues with this form validation
P粉296080076
2023-08-31 17:10:00
<p>I'm using Laravel 5.8 and I've made this controller method to create some records in the database. </p>
<pre class="brush:php;toolbar:false;">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);
}
}</pre>
<p>But this will not work and returns this error: </p>
<h2><strong>The given data is invalid. </strong></h2>
<p>This is basically because of the form validation requests and when I remove these validations from the method it works just fine. </p>
<p>So what's wrong with the validation of those form requests that return this error? </p>
<p>If you know, please let me know...I'd really appreciate any thoughts or suggestions. </p>
<p>Thank you. </p>
You must specify exactly what you want to verify:
My code example:
When you use Laravel's validation, you should let Laravel handle errors because Laravel will automatically throw an exception when a rule fails. Therefore, the first suggestion is not to use try-catch blocks in validation routines.
As the Laravel documentation states: p>
Also, I recommend you not to use validation in your controller because according to good practice it is recommended to create a separate formRequest for validation, so you should slightly modify your controller to include a 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
which you should fill with:By using this approach, Laravel validates user input and manages any errors through exceptions.
greeting.