Search code examples
phplaravelhtml5-video

Retrieving video to stream returns empty in Laravel


I'm trying to stream a video file under Laravel public_path but it doesn't display the intended file. Here's what I have:

video.blade.php

<video width="100%" controls>
   <source src="{{ route('playVideo') }}" type="video/mp4">
</video>

web.php

Route::get('/playVideo', 'User\VideoController@show')->name('playVideo');

VideoController.php

public function show()
{
    
    $pathToFile = public_path('videos/videofile.mp4');

    return response()->file($pathToFile, [
        'Content-Type' => 'video/mp4',
        'Content-Length' => filesize($pathToFile),
    ]);
}

This is the result I have but I'm expecting the video here. enter image description here

This is the content when I Inspect Element it.

<source src="http://localhost:8000/playVideo" type="video/mp4">

Can someone help me figure out what I'm missing?


Solution

  • Oh jeez! After days of trying, I'm able let it work this way:

        $videoPath = public_path('videos/' . $videoName);
    
       // this following code disable direct acces to your video when accessing in URL
    
        $prev_url = url()->previous();
    
        if(str_contains($prev_url, 'stream/video.mp4') || $prev_url == url('/')){
            return abort(404);
        }
    
        $stream = new VideoStream($videoPath);
        $response = Response::stream(function () use ($stream) {
            $stream->start();
        }, 200, [
            'Content-Type' => 'video/mp4',
            'Cache-Control' => 'no-cache, no-store, must-revalidate',
            'Pragma' => 'no-cache',
            'Expires' => '0',
            'Content-Length' => $stream->getSize(),
            'Content-Disposition' => 'inline',
            'X-Content-Type-Options' => 'nosniff',
        ]);
    
        $response->send();