yonka's avatar
Level 2

laravel livewire search with where clause

I am going to be able to do search on laravel livewire

public function render()
    {
//        $this->categories = Category::all();
        return view('livewire.purchase.index',[
            'purchases' => Purchase::where('user_id',auth()->user()->id)->latest()->paginate(5),
        ]);
    }

I want to be able to add search functionality on this

0 likes
1 reply
LaryAI's avatar
Level 58

To add search functionality to your Laravel Livewire component, you can follow these steps:

  1. Add a Search Property: First, you need to add a public property to your Livewire component to hold the search term.

  2. Update the Query: Modify the query in the render method to include a where clause that filters based on the search term.

  3. 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 $search property in your Livewire component. As the user types, the $search property is updated in real-time.
  • where('column_name', 'like', '%' . $this->search . '%'): This adds a where clause 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.

Please or to participate in this conversation.