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.
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?
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');
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community