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 on Laravel Daily
Laravel 13 Starter Kit Teams and Customizations
10 lessons
33 min
Roles and Permissions in Laravel 13
14 lessons
57 min
How to Structure Laravel 13 Projects
16 lessons
1 h 32 min read