Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

I found a better solution to my problem thanks to Comyn on IRC:

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

But I'd still like to know why the accessor wasn't working.

0

Your 'getTotalAttribute()' accessor [if it is doing what I think it's doing] should be declared static. What was the error message that you were getting?

Last updated 9 years ago.
0

If I'm not wrong, the accessor works only for one model (or, in this case, for each Point model). In fact, what you need is a total for a collection of models, that's why "Auth::user()->points->sum('amount');" works.

If you put the accessor logic in the User model, it will probably work, since User has a collection of points:

// User model
public function getTotalAttribute() {
    $balance = 0.00;
    foreach($this->points as $point)
        $balance += $point->amount;
    return $balance;

    // Or this:
    // return $this->points->sum('amount');
}
Last updated 9 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.