Search code examples
laravellaravel-bladelaravel-livewirelaravel-9livewires

How to set active class dynamically on foreach element laravel 9


I want to set an active class when I clicked it on foreach element, I have this code but it makes all looping elements active, I just want to set an active class when I click on element I clicked, like the nav menu active but this case is in foreach element,

sorry my english is bad

here is my code

 <div class="border-0 border-r border-slate-800 pr-2">
     <h3 class="font-semibold">Kategori</h3>
     <div class="mt-6 space-y-6 text-slate-500">
          <a href="{{ route('shop') }}" class="{{ Route::is('shop') ? 'active' : '' }} kategori-link">
             All Product
          </a>

          @foreach ($ctg as $c)
              <a href="{{ route('shop.category', $c->slug) }}"
                 class="{{ Route::is('shop.category', $c->slug) ? 'active' : '' }} kategori-link">
                 {{ $c->name }}
              </a>
          @endforeach

     </div>
</div>

Solution

  • Instead of:

    class="{{ Route::is('shop.category', $c->slug) ? 'active' : '' }} kategori-link"
    

    If you use this, you can activate the category on the active page:

    @class([
        'kategori-link',
        'active' => route('shop.category', $c->slug) == request()->url()
    ])
    

    Add it like an attribute.