netdjw
netdjw

Reputation: 6007

How to return image in Laravel 6?

I have this code:

public function showImage($id) {
    $item = File::find($id);

    return response()->file($item->file_name_and_path);
}

$item->file_name_and_path contains the following:

files/2020/04/29/myfile.jpeg

Now I always get a FileNotFoundException.

The image file is on local driver in this path:

{laravel root}/storage/app/files/2020/04/29/myfile.jpeg

How can I get the correct local path or simply return the image file with image HTTP headers?

Upvotes: 2

Views: 1421

Answers (1)

Remul
Remul

Reputation: 8252

You could use the Storage facade for this:

use Illuminate\Support\Facades\Storage;

public function showImage($id) {
    $item = File::find($id);

    return Storage::response($item->file_name_and_path);
}

As you can see here, it will add the following headers to the response:

'Content-Type'
'Content-Length'
'Content-Disposition'

Upvotes: 2

Related Questions