How to define Laravel Validation Rules for Video Uploads?

We have covered uploading a video in Laravel in the previous tutorials. All data we upload or save to database requires validation. Similarly, it is required for uploading videos. In fact, video uploads require compulsory size and types validation to ensure the uploaded video supports application format and is of an optimized size to avoid heavy loads on the application. There are various ways to define validation rules for video uploads. Lets have a thorough look at each of them.

Laravel Audio & Video Validator is an amazing package that adds validators for audio and video files to your Laravel project. We can create many validation rules using these validators.

You can install the package using the command below.

composer require minuteoflaravel/laravel-audio-video-validator

Validation Rules for Video Uploads

Mimes type

The basic validation before uploading a view is to check the video file mime types. For example, as shown below.

'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'

This checks if the video to be uploaded has either one of the mentioned mime types.

Video or audio duration

We can check the duration of a video or audio file in many ways. There are separate rules to check if it is less than, in between, or more than a stated time.

$request->validate([
    'video ' => 'video|duration:90',
]);

To check if the file is a video file and the video duration is between 90 and 180 seconds.

$request->validate([
    'video ' => 'video|duration_min:90|duration_max:180',
]);

Video Dimensions

We can define a rule to check dimensions of a video to upload. This uploads a video, if it has the mentioned height and width.

$request->validate([
    'video' => 'video|video_width:1080|video_height:680',
]);

We can also check if the video lies between the mentioned dimensions.

$request->validate([
    'video' => 'video|video_min_width:1080|video_min_height:690',
]);

This will be applicable to videos with minimum width and height as mentioned above. For example, videos below the mentioned dimensions fail the validation rule, rest all will be uploaded.

Video Codecs

We can define a rule to check if a video has one of the mentioned codecs.

$request->validate([
    'video' => 'video|codec:mp3,pcm_s16le,m3u8',
]);