Sometimes, there are Laravel queries that only need to run under certain conditions. Previously, I used if-else
to do this. For example:
$filterCategoryId = $request->input('category_id'); $query = Post::query(); if ($filterCategoryId) { $query->where('category_id', $filterCategoryId); } $posts = $query->get();
The code above will take all data from the Post
model. If there is a category_id
filter from the request, the data will be filtered based on the category_id
column.
Although it's working, the code above can be written in a cleaner way using conditional clauses.
Conditional clauses in Laravel are done by adding the when
method to the query builder. Here's how:
- Move the
if
condition to the first argument of thewhen
method. - Move the query inside the
if
block to the second argument of thewhen
method as a closure.
For example:
$filterCategoryId = $request->input('category_id'); $posts = Post::when( $filterCategoryId, fn ($query) => $query->where('category_id', $filterCategoryId) )->get();
By using conditional clauses, the code will now look cleaner than using if-else
.
Top comments (4)
Does it look cleaner or clever? Anyone who knows PHP will understand the first example after reading it once. For the second example they have to investigate what is going on.
I rather write code others understand after one read.
For me, the second code looks cleaner because, in this case, i donโt need to create a separate variable for the query object or use if-else statements. But yeah, I agree that the first code is easier to understand after a first read.
I understand that fluent methods look great at first. When I found out that was possible, it was fluent methods everywhere.
But after a while I realized I needed the empty lines in the code. If the code is grouped good it is easier to find the parts I was searching for.
When I see the first example I can identify building the query and executing the query groups. With the second example it is all bunched together.
I think both forms of writing code have their place, just think of the others that will read the code.
This was such a well-written and thoughtful postโI really enjoyed the way you explained your ideas and offered a fresh perspective. Looking forward to reading more from you!