Skip to content
Advertisement

Laravel 8 Livewire search filter not working with first where clause

I want to have a table which shows all the data per company that has a filter search input, the problem is when I put the first argument where('company_id', Auth::user()->company_id) it bugs out and doesn’t make the filter search work.

$groups = Group::where('company_id', Auth::user()->company_id)
        ->orWhere('code', 'like', $filter)
        ->orWhere('name', 'like', $filter)
        ->orWhere('description', 'like', $filter)
        ->orWhereRaw("(CASE WHEN active = 1 THEN 'Active' ELSE 'Inactive' END) LIKE '%$filter%'")
        ->orderBy($this->column, $this->order)
        ->paginate($this->size);

This is my query for the table.

Advertisement

Answer

I suppose you want company_id filter to apply to all query and combine other orWhere conditions. The other orWhere should be grouped in query like this:

$groups = Group::where('company_id', Auth::user()->company_id)
            ->where(function ($query) use ($filter) {
                return $query->where('code', 'like', $filter)
                    ->orWhere('name', 'like', $filter)
                    ->orWhere('description', 'like', $filter)
                    ->orWhereRaw("(CASE WHEN active = 1 THEN 'Active' ELSE 'Inactive' END) LIKE '%$filter%'");
            })
            ->orderBy($this->column, $this->order)
            ->paginate($this->size);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement