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.
eugene007Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Laravel

From novice to tech pro — start learning today.