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