How to validate video duration in laravel?

by darrion.kuhn , in category: PHP Frameworks , 5 months ago

How to validate video duration in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 5 months ago

@darrion.kuhn 

To validate a video duration in Laravel, you can use the "after" rule in Laravel's validation system. Here's an example of how you can do this:

  1. Add a validation rule in your controller's validation method:
1
2
3
$validatedData = $request->validate([
    'video' => 'required|file|mimes:mp4,mov,avi|max:20000',
]);


  1. Add a custom validation rule using the "extend" method in the boot method of your AppServiceProvider:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use IlluminateSupportFacadesValidator;

Validator::extend('video_duration', function ($attribute, $value, $parameters, $validator) {
    $allowedDuration = 60; // Set the allowed duration in seconds here
    $video = new FFMpegFFMpeg();
    $stream = $video->open($value->path())->getStreams()->videos()->first();
    $duration = $stream->get('duration');

    if ($duration > $allowedDuration) {
        return false;
    }

    return true;
});


  1. Now, update the validation rule for the video in the controller's validation method:
1
2
3
$validatedData = $request->validate([
    'video' => 'required|file|mimes:mp4,mov,avi|max:20000|video_duration',
]);


This custom validation rule will check if the duration of the video uploaded by the user is less than or equal to the allowed duration (in the example above, 60 seconds). If the video duration is greater than the allowed duration, the validation will fail, and the user will receive an error message.