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
int age = (int) ((DateTime. Now - bday). TotalDays/365.242199);
Here is the query to calculate the age from D.O.B. The query is as follows. mysql> select StudentName,StudentDOB,year(curdate())-year(StudentDOB) as StudentAge from AgeDemo; The following is the output displaying age.
Dates can be instances of Carbon, which provides an assortment of helpful methods.
In your model, import the Carbon class:
use Carbon\Carbon;
And define an accessor:
/**
* Accessor for Age.
*/
public function age()
{
return Carbon::parse($this->attributes['birthdate'])->age;
}
You can then call age
as if it was a regular attribute. For example in a blade view:
<p>{{ $user->age() }} years</p>
To show directly in your view:
\Carbon\Carbon::parse($user->birth)->diff(\Carbon\Carbon::now())->format('%y years, %m months and %d days');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With