Skip to content
Advertisement

Boostrap popup from a loop in Laravel

I have content from a loop and I’m displaying title and image in a grid boxes. In addition, in every box of content I have View more button and when a user clicks on, it shows the full content (title, image, body) in popup.

I have tested with Bootstrap modal and the popup functionality works but when I click the View more from the first box or the second, the popup always shows the content from the first box.

How can I fix this, so when a user clicks on the “View more” from the second box, to show the full content from the second box?

Every content has also ID parameter from the database, for example the first box has ID 1 and the second box has ID 2, so how can I filter that popup by the ID of the content?

Here’s my code:

@foreach($drivings as $driving)
  <div class="col-sm-3">
    <div class="box-inner">
      <div class="image">
        <img class="img-fluid" src="{{ Storage::url($driving->image) }}" />
      </div>
      <div class="title">
        {{ $driving->title }}
      </div>
      <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
        View more
      </button>
      <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">{{ $driving->title }}</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="image">
              <img class="img-fluid" src="{{ Storage::url($driving->image) }}" />
            </div>
            <div class="modal-body">
              {!! $driving->body !!}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
@endforeach

Advertisement

Answer

You are targeting same id in each iteration #exampleModal. So, every button have same target with id #exampleModal.

So the solution is to append it with current driving id.

Assuming that you are using id for toggling modal, You can do something like this in button:

data-target="#exampleModal{{driving->id}}"

And in modal:

id="#exampleModal{{driving->id}}"

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