Search code examples
laravelaccessor

Laravel average value on accessor


I need to calculate average age of user.

here is my accessor code

public function getAgeAttribute()
{
    if ($this->birthday)
        return Carbon::parse($this->birthday)->age;
    else
        return 'Unknown';
}

How can i calculate the average age from accessor? Thanks for any help..


Solution

  • In your User.php:

    public function getAgeAttribute()
    {
      if ($this->birthday)
        return Carbon::parse($this->birthday)->age;
      else
        return 'Unknown';
    }
    

    If you want to calculate the average age of ALL users, place this where you need it:

    User:all()
        ->where('age', '!=', 'Unknown')
        ->avg('age');
    

    This will simply not include the users without a birth date, as it wouldn't make sense.

    If the birthday attribute is in the users table, it will be more efficient to not select users without a birthday date:

    User:whereNotNull('birthday')
        ->get()
        ->avg('age');