• Status: Solved
  • Priority: Low
  • Security: Public
  • Views: 60
  • Last Modified:

Simplify the Laravel Eloquent (Sort) (Where)

I would like to find out whether is there a way to perform the following:

1) Include (when $id is not null) and exclude (when $id is null) in the where clause for the code below.
2) Switch between sortByDesc and sortBy based on condition ($sort=='asc' then.... $sort=='desc' then...) for the code below.

if($id){
   $maxlimit = Product::where('category_id_fk',$id)->with(['child','price','variant','thumbnail','image','description'])->count();
   $products = Product::where('category_id_fk',$id)->with(['child','price','variant','thumbnail','image','description'])->take($recperpage)->get()->sortByDesc('price.list_price');
}else{
   $maxlimit = Product::with(['child','price','variant','thumbnail','image','description'])->count();
   $products = Product::with(['child','price','variant','thumbnail','image','description'])->take($recperpage)->get()->sortByDesc('price.list_price');
}

Open in new window


The objective is to simplify the code above as much as possible but achieve the same result.

Your help is kindly appreciated.
0
eugene007
Asked:
eugene007
1 Solution
 
eugene007Author Commented:
I found the solution and it's free of charge:

$sort = 'desc';

$searchResultQuery = Product::query();
$searchResultQuery =($id)?$searchResultQuery->where('category_id_fk',$id):$searchResultQuery;
		
$maxlimit = $searchResultQuery->with(['child','price','variant','thumbnail','image','description'])->count();
$products = $searchResultQuery->with(['child','price','variant','thumbnail','image','description'])->take($recperpage)->get();
$products = ($sort=='asc')?$products->sortBy('price.list_price'):$products->sortByDesc('price.list_price');

Open in new window


Thank You.
1
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now