I have a component inside a livewire component. but foreach only pass the last element to component. whenever I click the card, modal shows the same course info
cards inside foreach (livewire component)
@foreach($this->courses as $course)
<a @click='showModal = true' id="{{$course->id}}">
<div class="px-8 py-6">
<h2 class="text-base font-bold flex items-center mt-3">
{{ $course->title }}
</h2>
<div class="">
<div class="flex items-center">
{{ $course->desc }}
</div>
</div>
</div>
</a>
<x-sections.course-modal :course="$course"/>
@endforeach
modal (component)
<div id="{{$course->id}}" class="" x-cloak x-show="showModal">
<div class="px-14 pb-6">
<h2 class="">
{{ $course->title }}
</h2>
</div>
</div>
2
Answers
Instead of passing
course id
pass theloop index
using$loop->index
. I guess this should solve your problem.First, you have 2 elements with the same ID. This is never a good practice. Convert the modal ID to e.g.
modal-{{$course->id}}
.Second, there is no differentiating factor for your
showModal
. Therefore, all modals will show, since they are in the same scope. You’re not showing us how you are creating theshowModal
data, however I assume you have anx-data="{'showModal': false}"
somewhere up in the hierarchy. Instead, wrap thex-data
in each loop to ensure the data is scoped to each individual modal: