13

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.

4
  • Were you able to hit controller when you call the URL? Like try dd('testing') under controller and see whether you can view testing Commented Jan 23, 2017 at 5:20
  • @SaravananSampathkumar yes I was able to hit it. But if I copy the url of the image let say mysite/image/1 then it throws a 404 error Commented Jan 23, 2017 at 5:28
  • Strange, if you are getting 404 error while copying the url and pasting it separate tab then when were you able to hit controller? Commented Jan 23, 2017 at 5:31
  • @SaravananSampathkumar I tried doing a dd(Storage::get("123.png")); and was ablee to get a response of bytes content of the image. Meaning its working its just that it throws an error after that Maximum execution error Commented Jan 23, 2017 at 5:34

3 Answers 3

16

Have you tried

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Doesn't answer the original question.
0

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();

Comments

0

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 );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.