DEV Community

Ibrahim
Ibrahim

Posted on

Cleaner Laravel Queries: Use Conditional Clauses Instead of If-Else

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(); 
Enter fullscreen mode Exit fullscreen mode

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:

  1. Move the if condition to the first argument of the when method.
  2. Move the query inside the if block to the second argument of the when method as a closure.

For example:

$filterCategoryId = $request->input('category_id'); $posts = Post::when( $filterCategoryId, fn ($query) => $query->where('category_id', $filterCategoryId) )->get(); 
Enter fullscreen mode Exit fullscreen mode

By using conditional clauses, the code will now look cleaner than using if-else.

Top comments (4)

Collapse
 
xwero profile image
david duymelinck

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.

Collapse
 
ibrahimalanshor profile image
Ibrahim

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.

Collapse
 
xwero profile image
david duymelinck

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.

Collapse
 
devops_fundamental profile image
DevOps Fundamental

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!