Replace eloquent conditionals with "when"
So often we want to apply query conditions based on what a request sends in. Sometimes it's a "search by name" thing, other times we need to filter the records based on some status column.
public function index(Request $request)
{
$posts = Post::newQuery();
if ($request->term) {
$posts->where('name', 'LIKE', "%{$request->term}%");
}
if ($request->status) {
$posts->where('status', $request->status);
}
return view('posts.index', ['posts' => $posts->paginate()]);
}
I recently discovered an alternative to using conditionals. The when(condition, callback)
method executes the callback when the first parameter evaluates to true - still a conditional, but a bit cleaner.
The example above can be rewritten to this:
public function index(Request $request)
{
$posts = Post::query()
->when($request->term, fn($q, $term) => $q->where('name', 'LIKE', "%{$term}%"))
->when($request->status, fn($q, $status) => $q->where('status', $status));
return view('posts.index', ['posts' => $posts->paginate()]);
}
Tags: