Search code examples
laravellaravel-livewire

search bar not working using laravel livewire


here's the code for livewire whenever I run this code it shows nothing I am using laravel 7 and livewire for this approach.

For controller

<?php
namespace App\Http\Livewire;
use App\Models\brands;
use Livewire\Component;

class SearchBar extends Component
{
    
    public $searchTerm;

    public function render()
    {
        $searchTerm = '%'.$this->searchTerm.'%';
        return view('livewire.search-bar', [
            'users' => brands::where('Name', 'like', $searchTerm)->get()
        ]);
    }
}

For view

<div>
    <input type="text" placeholder="Search users..." wire:model='searchTerm'/>

    <ul>
        @foreach($users as $user)
            <li>{{ $user->Website }}</li>
        @endforeach
    </ul>
</div>

Solution

  • I think it should actually work. but if not, this is how i would write it. You do not need to pass the variables via the view() function.

    <?php
    namespace App\Http\Livewire;
    use App\Models\brands;
    use Livewire\Component;
    
    class SearchBar extends Component
    {
    
      public $searchTerm;
      public $users
    
      public function render()
      {
        $searchTerm = '%'.$this->searchTerm.'%';
        $this->users = brands::where('Name', 'like', $searchTerm)->get();
        return view('livewire.search-bar');
      }
    }
    

    I hope this works, otherwise maybe something is wrong with the livewire installation?