Josh Josh - 1 month ago 8
PHP Question

Returning Video file to a view on laravel 5.4

I am encountering a problem rendering video to my view in Laravel 5.4.

I have a view as follows:

<main class="video-player">
@if(!empty($video))
<video id="my-video" class="video-js vjs-big-play-centered" controls data-setup="{}">
<source src="{{url('video/'.$token.'/'.$video)}}" type="{{$video_mime_type}}">
<p class="vjs-no-js">
Please upgrade your browser.
</p>
</video>
@else
<div class="alert alert-info"><span class='fa fa-info-circle'></span> Lesson video is unavailable!!! </div>
@endif
</main>


The route for getting the video content is as follows:

Route::get('video/{token}/{video}','ResourceController@show_video');


And the ResourceController class is as shown below:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Storage;
use Response;
use File;
use GuzzleHttp\Mimetypes;
use App\Mime;

class ResourceController extends Controller
{

public function __construct()
{
$this->middleware('auth')->only('show_video');
}
........
........
public function show_video($token,$filename)
{
$token=\App\VideoPermission::where('token',$token)->first();
if(!empty($token))
{
$token->delete();
$mime_type=Mime::from_extension($filename);
return response()->file(storage_path('app/lesson-files/'.$filename),[
'Content-Type' => $mime_type,
'Content-Disposition' => 'inline; filename="Lesson-file"'
]);
}
return false;
}
}


When I play it on laptop browser, it plays well as expected but when I try to play the same video on a mobile phone browser (same Chrome browser on both situations), it throws the following exception:


UnexpectedValueException: The Response content must be a string or object implementing __toString(), "boolean" given. in /home/username/domainname.com/vendor/symfony/http-foundation/Response.php:409


Please could anyone help me figure out the source of the issue.
Thank you

Answer Source

I have later discovered that the problem is a result of an 'if' condition in the method that returns the file content. So, when the condition is not met for any reason, it returns 'false' as a response instead of the video file therefore resulting in the boolean response I receive.

That is the way the code is written to function when the required token is missing as shown below

if(!empty($token))
{ 
$token->delete();    
$mime_type=Mime::from_extension($filename);   
return response()->file(storage_path('app/lesson-files/'.$filename),[
    'Content-Type' => $mime_type,
    'Content-Disposition' => 'inline; filename="Lesson-file"'
    ]);
}
return false;

}

I later discovered that this happens when the user tries to access the application with an outdated browser which does not fulfill one of the conditions expected to return the video content.

In other words, the system is actually working as intended.

Thank you to all who tried to assist in one way or the other. I appreciate you all.