Level 73
The third parameter of when is the false part which means if the first condition is not true, then apply the latter. So I would replace this:
->when($request->name, function ($query) use ($request) {
$query->where('name', '=', $request->name);
})
->when($request->location, function ($query) use ($request) {
$query->where('location', '=', $request->location);
})
with this:
->when($request->name && $request->location, function($query) use ($request) {
$query->where(function($q) use ($request) {
$q->where('name', $request->name)->orWhere('location', $q->location);
});
}, function ($query) use ($request) {
$query->when($request->name, function ($query) use ($request) {
$query->where('name', '=', $request->name);
})
->when($request->location, function ($query) use ($request) {
$query->where('location', '=', $request->location);
});
})
1 like