I often run into the problem in Livewire to need a special treatment when a filter or search is empty. I copy a lot of code because I could not find a way to say: If empty, just return everything
.
Here’s a minimal example:
Not nice:
public $status = ''; // default, can also be 'yes' or 'no'
if (! $this->status)
{
return view('livewire.users', [
'users' => User::get(),
]);
}
return view('livewire.users', [
'users' => User::where('status', $this->status)->get(),
]);
Would be nicer:
public $status = '*'; // default, can also be 'yes' or 'no'
return view('livewire.users', [
'users' => User::where('status', $this->status)->get(),
]);
This would translate to User::where('status', *)
(any status, so return everything) in my dream implementation. This way I would not need a special case for the empty filter/search. I could not find a way in Eloquent to only use the where
if there is a value and just ignore it or return all records if the second parameter in where
is empty or a special character (just like *
).
Is there any way to say: If the where
column is empty, just don’t filter but return everything?