Display image from laravel controller

22,906

Have you tried

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

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

Share:
22,906

Related videos on Youtube

MadzQuestioning
Author by

MadzQuestioning

Updated on July 09, 2022

Comments

  • MadzQuestioning
    MadzQuestioning almost 2 years

    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.

Related