Debug School

rakesh kumar
rakesh kumar

Posted on

How to display dynamic data in Accordion using livewire

How to toggle data using livewire

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class AccordionComponent extends Component
{
    public $isOpen = false;

    public function toggleAccordion()
    {
        $this->isOpen = !$this->isOpen;
    }

    public function render()
    {
        return view('livewire.accordion-component');
    }
}
Enter fullscreen mode Exit fullscreen mode

In resources/views/livewire/accordion-component.blade.php:

<div>
    <button wire:click="toggleAccordion">Toggle Accordion</button>
    @if($isOpen)
        <div>
            <!-- Accordion content -->
        </div>
    @endif
</div>
Enter fullscreen mode Exit fullscreen mode

How to display dynamic data using livewire

Here's the complete code for the Livewire component controller and Blade file to achieve the functionality you described:

Livewire Component Controller (AccordionComponent.php)

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Category;

class AccordionComponent extends Component
{
    public $categories;
    public $isOpen = [];

    public function mount()
    {
        // Fetch all categories from the database along with their titles
        $this->categories = Category::with('titles')->get();

        // Initialize isOpen array with default values
        foreach ($this->categories as $category) {
            $this->isOpen[$category->id] = false;
        }
    }

    public function toggleAccordion($categoryId)
    {
        // Toggle the accordion state for the clicked category
        $this->isOpen[$categoryId] = !$this->isOpen[$categoryId];
    }

    public function render()
    {
        return view('livewire.accordion-component');
    }
}
Enter fullscreen mode Exit fullscreen mode

Blade File (accordion-component.blade.php)

<div>
    @foreach ($categories as $category)
        <button wire:click="toggleAccordion('{{ $category->id }}')">{{ $category->name }}</button>
        @if ($isOpen[$category->id])
            <div>
                @if ($category->titles->count() > 0)
                    <ul>
                        @foreach ($category->titles as $title)
                            <li>{{ $title->name }} - {{ $title->description }}</li>
                        @endforeach
                    </ul>
                @else
                    <p>No titles and descriptions under this category.</p>
                @endif
            </div>
        @endif
    @endforeach
</div>
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)