Skip to main content
Quick Tip

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

Enjoyed This Tip?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.