Clone Query to Re-Use It

What if you need to re-use the same query base, adding different additional conditions to it later?

You can create a query and then clone it if you wish. Example: a query for getting products created on a particular day. And then later, you want to query active and inactive products from that.

$query = Product::query();
 
$today = request()->q_date ?? today();
if($today) {
$query->whereDate('created_at', $today);
}
 
// Lets get active and inactive products
// Reusing $query variable
$active_products = $query->where('status', 1)->get(); // this line modified the $query object variable
$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.

So, we need to clone this $query before doing any $query modification action.

$active_products = $query->clone()->where('status', 1)->get(); // it will not modify the $query
$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:
  • 68 courses (1183 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses