Monday, March 7, 2022

[FIXED] Calculate Age from date stored in database in Y-m-d using Laravel 5.2

Issue

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 Age?

  • 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.

  • I am using something as below 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 my 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


Solution

To show directly in your view:

\Carbon\Carbon::parse($user->birth)->diff(\Carbon\Carbon::now())->format('%y years, %m months and %d days');


Answered By - Gabriel Glauber

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.