Search code examples
laravelforeachhideshowalpine.js

Alpinejs Hide/Show element inside laravel foreach loop


I am using alpinejs with laravel for a project, for every row of data i want to add hide/show button to show a descritption , the problem when i press show every decription inside foreach show and same for hide

  @foreach ($positives as $positive)
            <!-- Card -->
            <div class="bg-white rounded-lg  p-4 shadow-xs dark:bg-gray-800">
                <div class=" flex items-center justify-between p-4 bg-white rounded-lg 
                        dark:bg-gray-800">
                    <div class="flex items-center">
                        <div
                            class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:text-orange-100 dark:bg-orange-500 grow-0">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24"
                                stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round"
                                    d="M12 8v13m0-13V6a2 2 0 112 2h-2zm0 0V5.5A2.5 2.5 0 109.5 8H12zm-7 4h14M5 12a2 2 0 110-4h14a2 2 0 110 4M5 12v7a2 2 0 002 2h10a2 2 0 002-2v-7" />
                            </svg>
                        </div>
                        <div>
                            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                                {{$positive->name}}
                            </p>
                            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                                376
                            </p>
                        </div>
                    </div>



                    <div class=" cursor-pointer mb-8" @click="isDescriptionOpen=!isDescriptionOpen">
                </div>

                <div x-show="isDescriptionOpen"> 
                 <p>  description </p>
                </div>

                
            </div>
            <!-- Card -->
            @endforeach

Solution

  • The problem here is that you don't have multiple components created.

    Instead of:

     <!-- Card -->
     <div class="bg-white rounded-lg  p-4 shadow-xs dark:bg-gray-800">
    

    you should have

     <!-- Card -->
     <div class="bg-white rounded-lg  p-4 shadow-xs dark:bg-gray-800" x-data="{isDescriptionOpen: false}">
    

    and you should remove outer component that you probably created for isDescriptionOpen data.