To add search functionality to your Laravel Livewire component, you can follow these steps:
-
Add a Search Property: First, you need to add a public property to your Livewire component to hold the search term.
-
Update the Query: Modify the query in the
rendermethod to include awhereclause that filters based on the search term. -
Add a Search Input: In your Blade view, add an input field to capture the search term and bind it to the Livewire component.
Here's how you can implement these steps:
Step 1: Add a Search Property
In your Livewire component, add a public property for the search term:
use Livewire\Component;
use Livewire\WithPagination;
class PurchaseIndex extends Component
{
use WithPagination;
public $search = '';
public function render()
{
return view('livewire.purchase.index', [
'purchases' => Purchase::where('user_id', auth()->user()->id)
->where(function($query) {
$query->where('column_name', 'like', '%' . $this->search . '%');
})
->latest()
->paginate(5),
]);
}
}
Step 2: Update the Query
In the render method, update the query to include a where clause that filters based on the search term. Replace 'column_name' with the actual column you want to search.
Step 3: Add a Search Input
In your Blade view (livewire.purchase.index), add an input field for the search term and bind it to the Livewire component:
<div>
<input type="text" wire:model="search" placeholder="Search purchases...">
<table>
<!-- Your table structure -->
@foreach($purchases as $purchase)
<tr>
<td>{{ $purchase->id }}</td>
<td>{{ $purchase->name }}</td>
<!-- Other columns -->
</tr>
@endforeach
</table>
{{ $purchases->links() }}
</div>
Explanation
wire:model="search": This binds the input field to the$searchproperty in your Livewire component. As the user types, the$searchproperty is updated in real-time.where('column_name', 'like', '%' . $this->search . '%'): This adds awhereclause to filter the results based on the search term. Make sure to replace'column_name'with the actual column you want to search.
With these changes, your Livewire component will now support search functionality, filtering the purchases based on the user's input.