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
[NEW] Building a Typical Laravel SaaS
8 lessons
1 h 07 min
PhpStorm Junie AI for Laravel Projects: Crash Course
7 lessons
36 min
Laravel HTTP Client and 3rd-Party APIs
7 lessons
50 min