Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display image from laravel controller

Tags:

php

laravel-5

Would like to ask if anyone has ever tried to display an image from a Laravel Controller. Below is my code to a Laravel Controller. So basically I just want to hide the actual url of image and add additional validation so I decided to the image call my laravel URL.

Blade code that call the laravel controller

<img src="/image/1">

Route

Route::get('/image/{image_id}', ['as' => 'site.viewImage', 'uses' => 'ImageController@viewImage']);

Controller

public function viewImage($image_id)
{
    return Storage::get($image_id . '.png');
}

But this return an error not-found. Am I doing something wrong here? Note: I'm passing it to the controller because I need to do additional valdiation and to obfuscate the actual url of the file

I tried this code and its working but I would like a laravel type of approach

header("Content-type: image/png");
echo Storage::get($image_id .'.png');exit;

I also tried this approach

$response = response()->make(Storage::get($image_id . '.png'), 200);
$response->header("Content-Type", 'image/png');
return $response;

The laravel approach throws a 404 error.

like image 544
MadzQuestioning Avatar asked Jan 23 '17 05:01

MadzQuestioning


Video Answer


1 Answers

Have you tried

return response()->file($filePath);

See: https://laravel.com/docs/5.3/responses#file-responses

like image 128
Indy Avatar answered Oct 17 '22 13:10

Indy