To make the search bar work globally with Livewire, you need to ensure that the Livewire component handling the search functionality is aware of the context it's being used in (e.g., users page, products page). Here's a step-by-step solution to achieve this:
- Create a Livewire component for the global search bar.
php artisan make:livewire GlobalSearch
- In the
GlobalSearchcomponent, you'll need to have a property that holds the current search term and a method to perform the search based on the current page context.
namespace App\Http\Livewire;
use Livewire\Component;
class GlobalSearch extends Component
{
public $search = '';
public $context = '';
public function mount($context)
{
$this->context = $context;
}
public function updatedSearch()
{
// Perform search based on context
// You can emit an event or call a method to update the parent component
$this->emit('onSearch', $this->search, $this->context);
}
public function render()
{
return view('livewire.global-search');
}
}
- In your
global-search.blade.phpview, you'll have the search input:
<div>
<input wire:model.debounce.300ms="search" type="text" class="form-control" placeholder="Search...">
</div>
- In each of your page components (e.g.,
UsersIndex,ProductsIndex), you'll need to listen for theonSearchevent and handle the search accordingly.
protected $listeners = ['onSearch' => 'handleSearch'];
public function handleSearch($searchTerm, $context)
{
if ($context === 'users') {
// Search users logic
} elseif ($context === 'products') {
// Search products logic
}
// ... handle other contexts
}
- When you include the
GlobalSearchcomponent in your layout, pass the current context to it. For example, in yourusers.indexview:
<x-app-layout>
<x-slot name="pageTitle">
{{$pageTitle}}
</x-slot>
@livewire('global-search', ['context' => 'users'])
@livewire('admin.users.index')
</x-app-layout>
- Finally, make sure that your main layout (
app-layout) is set up to display the search component correctly.
By following these steps, you'll have a global search bar that is aware of the current page context and can perform searches accordingly. Remember to update your Livewire components to handle the search logic based on the context they receive.