Error : The Response content must be a string or Object implementing __toString(), "Object" Given

Asked

Viewed 969 times

2

I use Laravel 5.3 and I’m having this problem:

The Response content must be a string or Object implementing __toString(), "Object" Given,

when I try to use a route which returns an image of a particular user of my system, follows 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 }}">

1 answer

2


Problem: Missed importing the namespace of class Response:

use Illuminate\Http\Response;

or, then it can be used like this:

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

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

has an adjustment that is to pass along to this answer the type of the image, in the code below it was explained as it would be the ideal code.


Ideal code:

It has a much simpler way 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 the content-type with the image type that is written to disk is an important factor in this type of image loading, see in the code example that has already been automatically entered the content-type and this function does not need to worry about the namespace

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.