Search code examples
phpmysqllaravelreusability

Laravel | Reuse Query Variable instead of query duplication


I am trying to reuse a query variable, but looks like it takes the last assigned value not the original one, here's what I mean:

$categories = DB::table('invoice_detail')
            ->selectRaw('SUM(qty) as qty')
            ->where('loc_id', '=', $user->loc_id)
            ->join('items', 'invoice_detail.item_id', 'items.barcode')
            ->where('items.active', '1')
            ->join('categories', 'items.category_id', 'categories.id')
            ->addSelect('categories.name')
            ->groupBy('categories.name');
        dump($categories->get()); //It returns whole products, which is OK.
        $topCategories  = $categories->orderBy('qty', 'DESC')->take(5)->get();
        dump($categories->get()); // It returns the top products, not the original value.
        $downCategories = $categories->orderBy('qty', 'ASC')->take(5)->get();

I want to reuse the $categories variable to get the Top Products and Down Products without query duplication.

But in the first dump, it returns whole products, which is OK, then after getting the Top Products, it returns the top products, not the original value.

Any suggestions?


Solution

  • You could always use __clone method to make a copy of certain object if and only if that object has __clone method implemented:

    $topCategories= clone $categories;
    $topCategories->orderBy('qty', 'DESC')->take(5)->get();
    $downCategories = clone $categories;
    $downCategories->orderBy('qty', 'ASC')->take(5)->get();