Laravel Image Tutorials: Displaying an image

Written by SarahS

5th May 2020

In the first instalment of how to add an image in Laravel, we added the image to the database and stored it in the Laravel Storage folder to be used later.

In this instalment we will now use that image and display it on the page.

Displaying an Image

First we need a route to the animalphotos/show file, the route I am using is for the index page because I have more than one image to display:

Route::get('/animals/{animal}/photos/', 'AnimalPhotoController@index')->name('');

In the AnimalPhotoController.php this is the code to take the user to the Index page, this shows all the images for a particular animal:

public function index(Animal $animal)
        $animal_id = $animal->id;

        $animalPhotos = $animal->animalPhotos()
                ->where('animal_id', $animal_id)
        // passing data into view
        return view('animalPhotos/index', compact('animal', 'animalPhotos'));

In the index file I then have a @foreach which iterates through each photo (along with any other information about it in the database and displays it in a table:

@foreach($animalPhotos as $animalPhoto)
<table class="table">
<th>File Name</th>
<td><img src="{{asset('storage/images/'.$animalPhoto->name)}}" width="200px" /></td>
<form action="{{ route('', [$animal, $animalPhoto]) }}" method="POST">@csrf

And there you have a table with all the images associated with this animal. You will also see a button to delete the image which is what we will move onto next.

This is one of my Laravel posts.  I’m still learning Laravel so the posts are usually pretty basic and are more aimed at keeping track of things that I find useful so that I can come back to them again at a later date.  I hope you find them useful too.  If not, or if you think they are wrong then please leave a comment below.  Thank you.

Faster Laravel Hosting

If this post helped you or if you have any questions please leave me a comment below:


Submit a Comment

Your email address will not be published. Required fields are marked *

You May Also Like…

Setting up SQLite for Laravel

Setting up SQLite for Laravel

Sometimes you may decide you want to use SQLite for your Laravel app instead of a full blown MySQL database. In that...