Skip to content
Advertisement

Get all images from the database and display the images in a bootstrap 4 carousel Laravel 5.8

I’ve been trying to get all the images from the database and trying to display them in a bootstrap carousel but it is only returning one image.

                        <div class="carousel-item active">
                            @if($posts->active == 1)
                            <img  src="{{ Storage::url("image/{$posts->image}") }}" alt="..." class="d-block img-fluid">
                            @endif
                            <div class="carousel-caption d-none d-md-block">
                                <h3 class="text-white">{{ $posts->title }}</h3>
                                <p>{{ $posts->h1 }}</p>
                            </div>
                        </div>

And here is the code in the controller index function

$posts = Post::latest()->first();

When I try to change the method to get() instead of first() an error appears. I’m not sure if I need to setup a new variable for the images, or include a foreach in the view which I’m not sure how to do. Really appreciate the help.

Advertisement

Answer

<div class="carousel-item active">
@foreach($posts as $post)
    @if($post->active == 1)
        <img src="{{ Storage::url("image/{$post->image}") }}" alt="..." class="d-block img-fluid">
    @endif
    <div class="carousel-caption d-none d-md-block">
        <h3 class="text-white">{{ $post->title }}</h3>
        <p>{{ $post->h1 }}</p>
    </div>
@endforeach

</div>

You can access your posts like this if you are using get() method. Since first() method directly returns you the model you can access its properties but for get() you will have to loop through it since it returns “Eloquent Collection’ (not array, you can use toArray() if you need one).

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement