How to calculate age using query builder in laravel?

折月煮酒 提交于 2019-12-11 15:25:45

问题


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

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