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
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 getAgeAttribute()
{
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');
Calculating the age in Laravel is best done using the build in Carbon. Dates returned in Laravel are already in a Carbon format.
This logic should go in the model as a default getter for your model.
public function getAge(){
$this->birthdate->diff(Carbon::now())
->format('%y years, %m months and %d days');
}
This will result in "23 years, 6 months and 26 days"
Checkout the http://carbon.nesbot.com/docs/ docs for all the fun stuff you can do with it.
Assuming you are using models in your view and since you should make a getAge() function in that model.
You can call your model in the view as $user->getAge()
Thanks for all you suggestion.
That was easy and awesome with carbon.
I added this code in Model:
public function age() {
return $this->dob->diffInYears(\Carbon::now());
}
I also manage to get change the date format 'Y-m-d' from database to passing date in this 'd-m-Y' in view .
I place this code in model
public function getDOB(){
return $this->dob->format('d-m-Y');
}
来源:https://stackoverflow.com/questions/35524482/calculate-age-from-date-stored-in-database-in-y-m-d-using-laravel-5-2