Laravel provides a very powerfull set of validation rules (https://laravel.com/docs/5.6/validation) but seems don't provide a method to validate a video file duration.
By the way Laravel has the Validator::extend() method to add some custom rules. You can check out the whole rule from the below link: Laravel Custom Validation rules.
So we need to create our custom rule.
First open your AppServiceProvider.php and the create a new custom rule called video_lenght in the boot function:
public function boot()
{
/** others code here */
/** video duration validation 'video:25' */
Validator::extend('video_length', function($attribute, $value, $parameters, $validator) {
// validate the file extension
if(!empty($value->getClientOriginalExtension()) && ($value->getClientOriginalExtension() == 'mp4')){
$ffprobe = FFMpeg\FFProbe::create();
$duration = $ffprobe
->format($value->getRealPath()) // extracts file information
->get('duration');
return(round($duration) > $parameters[0]) ?false:true;
}else{
return false;
}
});
};
Then in order to use the new validation rule put in your controller VideoController.php
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'video' => 'video_length:25', // 25 max video length in second
]);
if ($validator->fails()) {
return redirect('video/create')
->withErrors($validator)
->withInput();
}
// Store the video post...
}
In order this code can works you need to has installed in your server
FFmpeg and pbmedia/laravel-ffmpeg a package that provides an integration with FFmpeg for Laravel 5.6