Awminux
Awminux

Reputation: 103

add filter to table using laravel and livewire

I'm trying to create a filter using laravel and livewire. My filter will have a selectbox with this items:

i want when user select active from selectbox, i want the items that are active to be displayed. I wrote the code like this but it doesn't work! what is the problem?

public $filter_buy_status = '';

public function render()
{
    if ($this->loadData == true) {
        $coins = Coin::where('name', 'like', '%'.$this->search.'%')
            ->orWhere('symbol', 'like', '%'.$this->search.'%')
            ->where('buy_status' , $this->filter_buy_status)
            ->get();
    } else {
        $coins = [];
    }
    return view('livewire.backend.crypto.coins')->with('coins' , collect($coins)->paginate($this->perPage));
}

Upvotes: 0

Views: 1681

Answers (1)

Qirel
Qirel

Reputation: 26470

Since you haven't shown your select-element, let's assume that it looks something like this, where "show all" is an empty value.

<select wire:model="filter_buy_status">
    <option value="">Show All</option>
    <option value="active">Show Active</option>
    <option value="inactive">Show Inactive</option>
</select>

Then, because an empty string is a "falsy" value (meaning that if you do if ("") it will be false), we can apply the condition using when(). This is a Laravel filter method that is only applied when the condition in when() is true.

Its also important to group your WHERE conditions. If you want the filter of status to be applied to all, and then search "where symbol OR where name", then your SQL would look like this

WHERE buy_status = 'Active' AND (name LIKE '%search%' OR symbol LIKE '%search%')

In Laravel, that means that you group all the orWhere() in a grouped where(), like this

$coins = Coin::where(function($query) {
    return $query->where('name', 'like', '%'.$this->search.'%')
        ->orWhere('symbol', 'like', '%'.$this->search.'%');
    })
    ->when($this->filter_buy_status, function($query, $status) {
        return $query->where('buy_status' , $this->filter_buy_status);
    })
    ->get();

Upvotes: 3

Related Questions