I want to calculate the average age of users using their birth dates. I have a Model class called Member
, including a function to get the age of the user.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Member extends Model {
public static function averageAge() {
//What to do here
}
public function age() {
$birthDate = Carbon::parse($this->birthDate);
return $birthDate->diffInYears(Carbon::now());
}
}
Carbon has a method to calculate the “age” of a date, so you can do this in your model instead:
class Member extends Model
{
protected $casts = [
'birthDate' => 'date',
];
public function getAgeAttribute()
{
return $this->birthDate->age;
}
}
If you’re wanting to calculate the average age of multiple members, then I’d create a class that takes a collection of members and returns that value:
class AverageAge
{
public static function forMembers(Collection $members)
{
return $members->average(function ($member) {
return $member->age;
});
}
}
Which you can then use like this:
$members = Member::where(...)->get();
$averageAge = AverageAge::forMembers($members);