Support the ongoing development of →
Database Eloquent
Last updated 10 months ago.

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


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


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 8 years ago.

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 8 years ago.

Sign in to participate in this thread!

Full Stack Europe

Your banner here too?


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

Your logo here?

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

© 2023 - All rights reserved.