问题
I have saved the date of birth in MySQL database.
table name : **users**
field name : **dob**
now I want to show age on view. My query is :
$user_info = DB::table('users')->select('(year(curdate())-year(dob)) as age')->get();
I'm using Laravel 5.5.
but this is creating error. How to calculate age using query builder in laravel?
回答1:
I recommend you to make a custom attribute in your app/User.php
model.
For example:
In your User.php
public function getAgeAttribute() {
return $this->dob->diffInYears(\Carbon\Carbon::now());
}
In the controller
and/or view
you can now access this method as a attribute, by doing the follow:
Auth::user()->age;
This will set a attribute in your User model based on the getAgeAttribute()
.
For more information, take a look at: https://laravel.com/docs/5.6/eloquent-mutators#accessors-and-mutators
回答2:
You can use selectRaw
and then use mysql function like this
$user_info = DB::table('users')
->selectRaw("TIMESTAMPDIFF(YEAR, DATE(dob), current_date) AS age")
->get();
回答3:
you can define a function in your model like this
public function age() {
return $this->dob->diffInYears(\Carbon::now());
}
after that you can call it like this
{{ $user->age() }}}
来源:https://stackoverflow.com/questions/51653672/how-to-calculate-age-using-query-builder-in-laravel