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

吃可爱长大的小学妹 提交于 2019-12-03 03:05:54

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');
Frederiek

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'); 
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!