Home > Software design >  How to use eloquent builder to fetch results twice
How to use eloquent builder to fetch results twice

Time:10-02

How do I use one query builder to fetch results twice? With Carbon I have use CarbonImmutable to achieve this but with eloquent, one fetch is affecting the others down the line.

Here is the code.


$expenses = PropertyExpense::with(['bill'])
            ->where('contractor_id', $supplier);

/* I run this to get balance brought forward */

$oldDebits = $expenses->whereDate('txn_date', '<', $start)
            ->sum('billed'); //here I get actual bbf value.

/* Then I run this to get the debits for the start and end period */
$debits = $expenses
            ->whereDate('txn_date', '>=', $start)
            ->whereDate('txn_date', '<=', $end)
            ->get(); //Here I get empty array. Which should not be the case.

When I remove the $oldDebits Section, I get the Collection of all debits as expected. I have even rewritten the code to temporarily assign expenses to another variable before executing the sum to no avail. Here.


$olderDebits = $expenses;
$oldDebits = $olderDebits->whereDate('txn_date', '<', $start)->sum('billed');

When I ran this, am still getting the same results: correct $oldDebits and an empty collection for $debits.

Any assistance?

Am using Laravel V9 and PHP 8.1.

CodePudding user response:

That is because you ->whereDate() on to the same variable which is $expenses.

In your case, you should clone the query builder before execute it.

Such as

$expenses = PropertyExpense::with(['bill'])->where('contractor_id', $supplier);

$oldDebits = (clone $expenses)->whereDate('txn_date', '<', $start)->sum('billed');

$debits = (clone $expenses)
            ->whereDate('txn_date', '>=', $start)
            ->whereDate('txn_date', '<=', $end)
            ->get();
  • Related