I want to get all row, but I have to use where statement.
This is my code:
if($request->city == 'all') {
$city = 'Show all';
} else {
$city = $request->city;
}
$listing = List::where('city', $city)->get();
I have to use a where statement. What should I write instead of Show all?
Advertisement
Answer
Use when:
$listing = List::when($request->city != 'all', function ($query) use ($city) {
$query->where('city', $city);
})
->get();
when second parameter (closure) will execute only if the first parameter is a truish expression, in your case if the city value is not equal to all.
Updated
$fields = collect($request->all())
->filter(function (string $item) {
return $item != 'all';
});
$listing = List::when($fields->isNotEmpty(), function ($query) use ($fields) {
$fields->each(function ($value, $key) use ($query) {
$query->where($key, $value);
});
})
->get();