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

sanainfotech's avatar

Calculate Age from date stored in database in Y-m-d

Hi User's add their DOB through the Form that store in database,

I would like calculate age from stored date in the database which is in this format Y-m-d,

My Question is :

How to calculate ?

Where to put the logic , In Controller or Model?

How to pass the stored Date in view in this format 'm-d-Y'

How to pass the result of logic which is age in view.

This code is in my model. Is this right?

This is Controller:

public function index()   {   
 $profile   = User::find($this->userid())->profiledetailsHasOne;  //This has Dob field                   
 return view('profile.index',['profile' => $profile ]); 
}

This is Model

 public function getAge(){
        $this->birthdate->diff($this->attributes['dob'])
        ->format('%y years, %m months and %d days');
 }

This is my view:

<tr>
            <th>Age</th>
            <td>{{$profile->getAge()}}</td>
   </tr>

Is this Right? I am getting error as below

Call to a member function diff() on null
0 likes
5 replies
HRcc's avatar

You should be able to use Carbon's diffInYears to calculate age easily. Similarly, use Carbon to reformat the date for view. The logic could be placed in model directly (maybe as age getter) or presenter. I would avoid putting this to controller.

ohffs's avatar
ohffs
Best Answer
Level 50

If you use the dates feature on the model then you can (as @HRcc mentions) just be able to do (on your model) :

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

then to display it you would just do :

{{ $user->age() }}}

Edit: I see you've edited your question - hopefully the stuff above still gives you some pointers.

4 likes
sanainfotech's avatar

Thank s, @ohffs , That was easy and awesome with carbon.

How to change the format from datebase 'Y-m-d' to this 'm-d-Y' and pass to view?

ohffs's avatar

As your dob is now a carbon date in your views you can just do :

Date of birth : {{ $user->dob->format('m-d-Y') }}

Please or to participate in this conversation.