Chain conditional clauses to the query without writing if-else statements

The "when" helper in the query builder is🔥

You can chain conditional clauses to the query without writing if-else statements.

Makes your query very clear:

1class RatingSorter extends Sorter
2{
3 function execute(Builder $query)
4 {
5 $query
6 ->selectRaw('AVG(product_ratings.rating) AS avg_rating')
7 ->join('product_ratings', 'products.id', '=', 'product_ratings.product_id')
8 ->groupBy('products.id');
9 ->when(
10 $this->direction === SortDirections::Desc,
11 fn () => $query->orderByDesc('avg_rating')
12 fn () => $query->orderBy('avg_rating'),
13 );
14 
15 return $query;
16 }
17}

Tip given by @mmartin_joo

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord