Home > Software engineering >  Laravel 8 sum data on condition hasMany
Laravel 8 sum data on condition hasMany

Time:03-01

I always get error :

Property [payment] does not exist on this collection instance.

But i already set eloquent on User :

public function payment() { return $this->hasMany(Payment::class); }

Its not working when im use where and whereBetween. its sound good if i do like this :

User::first()->payment->sum('amount')

Example on tinker :

$l = User::whereBetween('created_at', ['2022-02-20', '2022-02-28'])->with('payment')->get()
$l->payment->sum('amount')

I need result only 1 row not in array. because im find grand total for table footer.

CodePudding user response:

Try this

$l = User::whereBetween('created_at', ['2022-02-20', '2022-02-28'])->with('payment')->get();

$grandTotal = $l->map(function ($item) {
    $item->total_amount = $item->payment->sum('amount');
    return $item;
})->sum('total_amount');

CodePudding user response:

You can add conditions to a relationship in the way mentioned below

$users = User::whereBetween('created_at', [
         '2022-02-20', '2022-02-28'
     ])->with(['payments'])
     ->get();

as you're fetching multiple users you need to iterate through the loop. That is what you were missing in your code

$users = $users->map(function ($user) {
            $user['total_payment'] = $user->payments->sum('amount');
            return $user;
        });

and then

$grandTotal = $users->sum('total_payment');
  • Related