Error: The Response content must be string or object implementing __toString (), "object" given

2

I use laravel 5.3 and am having this problem:

  

The Response content must be a string or object implementing __toString (), "object" given,

When I try to use a route that returns an image of a particular user from my system, follow the code below.

Here is the action of controller that returns the image.

public function getImage($filename)
{
    $file = Storage::disk('local')->get("/avatars/".$filename);

    return new Response($file, 200);
}

Route

Route::get('getImage/{filename}', 'TeatcherController@getImage')
      ->name('get.image')
      ->middleware('auth');

Using the route to get the image

  

<img src="{{ url(route('get.image', ['filename' => $user->teatchers->photoName] )) }}" alt="{{$user->teatchers->photoName }}">

    
asked by anonymous 27.12.2016 / 23:30

1 answer

2
Failed to import namespace from class Response :

  

use Illuminate\Http\Response;

or, so it can be used like this:

public function getImage($filename)
{
    $file = Storage::disk('local')->get("/avatars/".$filename);

    return new \Illuminate\Http\Response($file, 200);
}

There is a setting that is to pass next to that answer the type of the image, in the code below was explained what would be the ideal code.

Ideal code:

A much simpler way to do this is to use the function response :

public function getImage($filename)
{
    $file = Storage::disk('local')->get("/avatars/".$filename);
    $mimeType = (string)\Storage::disk('local')->mimeType("/avatars/".$filename);
    return response($file, 200, ['content-type' => $mimeType]);
}

Important: pass content-type with image type that is written to disk is an important factor in this type image loader, see in the code example that content-type was already automatically entered and this function does not have to worry about namespace

References:

28.12.2016 / 00:44