Reuse or clone query()

Typically, we need to query multiple time from a filtered query. So, most of the time we use query() method,

let's write a query for getting today created active and inactive products

1 
2$query = Product::query();
3 
4 
5$today = request()->q_date ?? today();
6if($today){
7 $query->where('created_at', $today);
8}
9 
10// lets get active and inactive products
11$active_products = $query->where('status', 1)->get(); // this line modified the $query object variable
12$inactive_products = $query->where('status', 0)->get(); // so here we will not find any inactive products

But, after getting $active products the $query will be modified. So, $inactive_products will not find any inactive products from $query and that will return blank collection every time. Cause, that will try to find inactive products from $active_products ($query will return active products only).

For solve this issue, we can query multiple time by reusing this $query object. So, We need to clone this $query before doing any $query modification action.

1$active_products = $query->clone()->where('status', 1)->get(); // it will not modify the $query
2$inactive_products = $query->clone()->where('status', 0)->get(); // so we will get inactive products from $query

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