Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

t0berius's avatar

total (using sum())

I've got three tables:

users
    -id
    -name
    -...

addresses
    -id
    -user_id
    -...

transactions
    -id
    -address_id
    -amount

Now I would like the whole sum of all transactions for a certain user. What's the best way to archive this using eloquent?

  dd($forwarded_total->sum('addresses.transactions.amount'));

returns 0 all the time.

0 likes
6 replies
StefanVoinea's avatar

You must have following relationships in your models

a users hasMany addresses an addrese belongsTo a user an addresse hasMany transactions a transaction belongsTo a addrese

and then for a user you can call

$user->adresses()->transactions()->sum('amount');

t0berius's avatar

@StefanVoinea

These are my relationships from my models:

user model:

    public function addresses()
{
    return $this->hasMany('App\Address');
}

address model:

    public function user()
{
    return $this->belongsTo('App\User');
}

public function transactions()
{
    return $this->hasMany('App\Transaction');
}

transaction model:

    public function address()
{
    return $this->belongsTo('App\Address');
}

Now when I try to use this in my view it says:

Call to undefined method Illuminate\Database\Query\Builder::adresses()

in my view I use:

{{ Auth::user()->adresses()->transactions()->sum('amount') }}
rcubitto's avatar

I'd suggest using Eloquent's hasManyThroughrelationship, since a User has many Transactions through the Address model.

// App/User.php
public transactions() {
    return $this->hasManyThrough(App\Transaction::class, App\Address::class);
}

Then, you can just do it like

Auth::user()->transactions()->sum('amount');

Much cleaner solution, since you don't have to be explicit about the Address model.

1 like

Please or to participate in this conversation.