Skip to content
Advertisement

Calculating variable using attribute laravel

I have a simple code where I output the new age of a person. If a person is aged 17, it should output 18.
But I’m calculating this on blade (which I think is bad). And I’m trying attribute to handle this, but since I’m very new to Laravel, I don’t know how to handle it.

Please help me…

This is how I calculate
{{date('Y') - $birth->birth_date->year + 1}}
It is decreasing the current year from the record and getting the current age, then adding 1.
Is there a more reliable way to do it (like using attribute)?

I’ve tried adding attribute to my eloquent but I can’t find the way

Advertisement

Answer

This is best defined as a mutator/accessor on your model:

User.php (or whatever $birth is)

use CarbonCarbon;

class User extends Model {
  protected $dates = ['birth_date'];

  public function getAgeAttribute() {
    return Carbon::now()->diffInYears($this->birth_date);
  }
  ...
}

Then, in your .blade.php file:

{{ $birth->age }} // 18 (or 17)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement