Search code examples
laravelbootstrap-4carousel

Carousel component with loops


Good day,

Could someone please advise as I am trying to use the Bootstrap Carousel component along with displaying different posts in a loop, in a Laravel application? The images from the different posts displays correctly, but the navigation links on all the posts triggers the slides on only the first post, while images of all the other post does't move. Please find the code below:

 @if(count($properties) > 0)
    @foreach($properties as $property)     

        <div class="col-lg-3 float-left" style="width: 220px;padding: 0px;padding-right: 0px;height: 275px;margin-left: 35px;margin-top: 10px;margin-bottom: 10px;">
            <div class="carousel slide" id="carousel-1">
                <div class="carousel-inner" role="listbox">

                    <div class="carousel-item active"><img class="img-fluid w-100 d-block" src="/storage/cover_images/{{$property->cover_image}}" alt="Slide Image" style="height: 175px;"></div>
                    <div class="carousel-item"><img class="w-100 d-block" src="storage/cover_images/{{$property->image2}}" alt="Slide Image" style="height: 175px;"></div>
                    <div class="carousel-item"><img class="w-100 d-block" src="storage/cover_images/{{$property->image3}}" alt="Slide Image" style="height: 175px;"></div>
                    <div class="carousel-item"><img class="w-100 d-block" src="storage/cover_images/{{$property->image4}}" alt="Slide Image" style="height: 175px;"></div>
                    <div class="carousel-item"><img class="w-100 d-block" src="storage/cover_images/{{$property->image5}}" alt="Slide Image" style="height: 175px;"></div>
                </div>

                <div>
                    <!-- Start: Previous --><a class="carousel-control-prev" href="#carousel-1" role="button" data-slide="prev"><span class="carousel-control-prev-icon"></span><span class="sr-only">Previous</span></a>
                    <!-- End: Previous -->
                    <!-- Start: Next --><a class="carousel-control-next" href="#carousel-1" role="button" data-slide="next"><span class="carousel-control-next-icon"></span><span class="sr-only">Next</span></a>
                    <!-- End: Next -->
                </div>

Solution

  • The href attribute decides which slide the button will points to, and it is currently all pointing to #carousel-1

    You need to change the id = "carousel-1" to id="carousel-{{$i}}"in your div id to the index of current property which you can achieve by @foreach ($properties as $i=>$property).

    The next thing is changing the href attribute of your <a> tag at <a class="carousel-control-prev" href="#carousel-1" role="button" data-slide="prev"><span class="carousel-control-prev-icon"></span><span class="sr-only">Previous</span></a> accordingly.