Search code examples
laravelvariablescomponentslaravel-blade

Laravel Blade property not being passed to the component nor to the class


I have the following HTML:

<div class="relative lg:inline-flex bg-gray-100 rounded-xl">
      <x-dropdown>
           <x-slot:trigger>
               <button>.......</button>
           </x-slot:trigger>

           <x-dropdown-item href='/' :active="request()->is('/')">All</x-dropdown-item>

           @foreach($categories as $category)
                <x-dropdown-item href="/category/{{ $category->slug }}"
                       :active="request()->is('/category/'.$category->slug)"> {{ ucwords($category->name) }}
                </x-dropdown-item>
           @endforeach
     </x-dropdown>
</div>

But the active property is not assigned in my dropdown-item component:

@props(['active' => false])
        
@php
    $classes = 'block text-left px-3 text-sm leading-5 hover:bg-blue-500 focus:bg-blue-500 hover:text-white focus:text-white';
    if ($active)   {
       dd($active);
       $classes .=' bg-blue-500 text-white';
    }
        
@endphp
        
        
<a {{ $attributes(['class' => $classes]) }}>{{ $slot }}</a>

I expect my dd to fire whenn the active property is set to true but it never does

I tried making a DropdownItem class:

<?php
    
    namespace App\View\Components;
    
    use Closure;
    use Illuminate\Contracts\View\View;
    use Illuminate\View\Component;
    
    class DropdownItem extends Component
    {
        /**
         * Create a new component instance.
         */
        public function __construct(...$args)
        {
            dd($args);
    //        $this->active = true;
        }
    
        /**
         * Get the view / contents that represent the component.
         */
        public function render(): View|Closure|string
        {
            return view('components.dropdown-item', [
    //            'active' => $this->active
            ]);
        }
    }

But $args returns [] so also no properties and i do not know why, i checked the official documentation for laravel 10 but everything seems to be allright. If i mannualy set active in the class everything works


Solution

  • <x-dropdown-item href=".." :active="request()->is('category/'.$category->slug)"> 
    {{ .. }}</x-dropdown-item>
    

    instead of

    <x-dropdown-item href=".." :active="request()->is('/category/'.$category->slug)"> 
    {{ .. }}</x-dropdown-item>
    

    ensuring that the path begins with a '/'.

    That fixes the issue without a DropdownItem class.

    If i want to use the DropdownItem class i must:

    remove @props(['active' => false]) (not required)
    php artisan optimize:clear