MadzQuestioning
MadzQuestioning

Reputation: 3762

Display image from laravel controller

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.

Upvotes: 13

Views: 33004

Answers (3)

Howard
Howard

Reputation: 3758

Old question but you can do something like this in Laravel 9.x.

Blade:

<img src="/image/1">

Route:

Route::get('/image/{id}', [ImageController::class, 'viewImage']);

Controller:

public function viewImage($id)
{
    // $image_path would look something like this: './images/abc.png'
    $image_path = $id.'.png';
    return response()->file( $image_path );
}

Upvotes: 0

saad
saad

Reputation: 1364

If you want to show file from public folder

$link=url('link/to/image/'.$imageName);
header("Content-type: image/png");
$imageContent = file_get_contents($link);
echo $imageContent; 
die();

Upvotes: 0

Indy
Indy

Reputation: 822

Have you tried

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

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

Upvotes: 16

Related Questions