Calculate Age from date stored in database in Y-m-d using Laravel 5.2
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');
I added this code in my Model:
protected $appends = ['age'];public function getAgeAttribute(){ return Carbon::parse($this->attributes['birthday'])->age;}