skip to Main Content

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


  1. Instead of passing course id pass the loop index using $loop->index. I guess this should solve your problem.

    Login or Signup to reply.
  2. 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 the showModal data, however I assume you have an x-data="{'showModal': false}" somewhere up in the hierarchy. Instead, wrap the x-data in each loop to ensure the data is scoped to each individual modal:

    @foreach($this->courses as $course)
        <div x-data="{'showModal': false}">
            <a @click='showModal = true' id="{{$course->id}}">
                {{-- // --}}
            </a>
            <x-sections.course-modal :course="$course"/>
        </div>
    @endforeach
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search