Steevie
Steevie

Reputation: 680

Show secured images with Laravel 5 and Blade

I don't want that users can access images from simply using a URL like http://laravel.dev/123.jpg. Therefore I store all images in the storage directory, instead of storing them in the public folder.

With a controller like this

public function show($id) {
    $img = storage_path('my_images/123.jpg');
    return response()->download($img, null, [], null);
}

the image is correctly displayed by Laravel 5, although it is stored outside from the public folder.

Great up to this point ... but I want to use Blade and surround the image with some more details. Therefore my controller looks like this

public function show($id) {
    $picture = Picture::find($id);
    $img = storage_path('my_images/123.jpg');
    return view('pictures.show', array('picture' => $picture, 'img' => $img));
}

and the view like this

<!DOCTYPE html>
<html>
    <head>
        <title>Picture {{ $picture->id }}</title>
    </head>
    <body>
        <h1>Picture {{ $picture->id }}</h1>
        <ul>
            <li>Name: {{ $picture->name }}</li>
            <li>Description: {{ $picture->description }}</li>
        </ul>
        <img src="{{ $image }}">
    </body>
</html>

which obviously does not work, because the location of the image is not publicly accessible (which ist the intention).

What do I have to use instead of <img src="{{ $image }}"> to make this work?

Upvotes: 1

Views: 82

Answers (1)

Mina Abadir
Mina Abadir

Reputation: 2981

Make the src attribute to call the URL of your first controller, this will work for you.

In other words, let's say, you have a route called image.show with that code.

public function show($id) {
    $img = storage_path('my_images/123.jpg');
    return response()->download($img, null, [], null);
}

So in your blade:

<img src={{route("image.show",$img_object)}}">

Upvotes: 1

Related Questions