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.
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
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.
Please or to participate in this conversation.