Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

philipbaginski's avatar

Calculate age based on date - Laravel Nova

Hi! It the table Stewards I have 'dob' column where are stored birthdays dates. I would like to calculate age from birthday. I tried to use in Steward model:

public function age() { return $this->dob->diffInYears(\Carbon::now()); }

, but I have no idea what to write in Resource file. Any help?

0 likes
8 replies
philipbaginski's avatar

Thank you. In resource file I made:

Text::make('DOB', function () { return $this->getAge(); }),

, and it displayed age as formated in model file.

Problem fixed :-)

ahmeddabak's avatar

If this answer helped you please mark this question as solved

philipbaginski's avatar

I faced another problem with age: the birthday is e.g. 20-02.2018. I would like all 2020 year how age of this person as 2 years old. Count diff between years, not diff between dates. Right now the age shows as 1 year old. Is there any method to make it?

My current code:

public function getAge() { return $this->dob->diff(Carbon::now()) ->format('%y years, %m months and %d days'); }

ahmeddabak's avatar

if someone is born on 20-02.2018 he is now one year old, till 20-02.20120 he will then be two years old.

but you need to calculate his age till the end of the current year, is this what you are trying to do?

philipbaginski's avatar

Yes, exacly. I need all year to have the same age. If someone was born on 01-01 or 31.12, all year I have to show as the same age. So, basically the age must be counted only based on the year, not month and day.

ahmeddabak's avatar
Level 47

try this, and if it works please mark this as solved

return $this->dob->diffInYears(\Carbon::now()->endOfYear());
philipbaginski's avatar

I solved it by using this code:

public function getAgeAttribute() { return $this->dob->startOfYear()->diffInYears(); }

in model. It works proper.

Please or to participate in this conversation.