BinaryFileResponse in Laravel undefined

I had the following problem: I want to return the image to the route / getImage / {id} The function looks like this:

public function getImage($id){ $image = Image::find($id); return response()->download('/srv/www/example.com/api/public/images/'.$image->filename); } 

When I do this, he returns me this:

 FatalErrorException in HandleCors.php line 18: Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header() 

I have use Response; at the beginning of the controller. I don't think the HandleCors.php problem is a problem, but anyway:

 <?php namespace App\Http\Middleware; use Closure; use Illuminate\Contracts\Routing\Middleware; use Illuminate\Http\Response; class CORS implements Middleware { public function handle($request, Closure $next) { return $next($request)->header('Access-Control-Allow-Origin' , '*') ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE') ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application'); } } 

I really don't know why this is happening because it is exactly as described in the Laravel Docs. I updated Laravel when I received an error, but this does not fix it.

+8
php symfony laravel
source share
1 answer

The problem is that you are calling ->header() on a Response object that does not have this function ( Symfony\Component\HttpFoundation\BinaryFileResponse ). The function ->header() part of the attribute that is used by the Laravel Response class , and not the base Symfony Response.

Fortunately, you have access to the headers property, so you can do this:

 $response = $next($request); $response->headers->set('Access-Control-Allow-Origin' , '*'); $response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE'); $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application'); return $response; 
+21
source share

All Articles