使用Laravel 5.2从Y-m-d中存储在数据库中的日期开始计算年龄 [英] Calculate Age from date stored in database in Y-m-d using Laravel 5.2

查看:157
本文介绍了使用Laravel 5.2从Y-m-d中存储在数据库中的日期开始计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,用户通过存储在数据库中的表单添加其DOB,

Hi User's add their DOB through the Form that store in database,

我想根据数据库中存储的日期来计算年龄,格式为Y-m-d,

I would like calculate age from stored date in the database which is in this format Y-m-d,

我的问题是:

  • 如何计算年龄?

  • How to calculate Age?

将逻辑放在控制器或模型的何处?

Where to put the logic , In Controller or Model?

如何以"m-d-Y"格式在视图中传递存储的日期

How to pass the stored Date in view in this format 'm-d-Y'

如何传递考虑年龄的逻辑结果.

How to pass the result of logic which is age in view.

我在模型中使用以下内容,对吗?

I am using something as below in my model is this Right?

这是控制者:

public function index()   {   
    $profile   = User::find($this->userid())->profiledetailsHasOne;  //This has Dob field                   
    return view('profile.index',['profile' => $profile ]); 
}

这是我的模特:

public function getAge(){
    $this->birthdate->diff($this->attributes['dob'])
    ->format('%y years, %m months and %d days');
}

这是我的观点:

<tr>
    <th>Age</th>
    <td>{{$profile->getAge()}}</td>
</tr>

这是对的吗?我收到如下错误

Is this Right? I am getting error as below

Call to a member function diff() on null

推荐答案

日期可以是Carbon的实例,它提供了各种有用的方法.

Dates can be instances of Carbon, which provides an assortment of helpful methods.

在您的模型中,导入Carbon类:

In your model, import the Carbon class:

use Carbon\Carbon;

并定义一个访问器:

/**
 * Accessor for Age.
 */
public function getAgeAttribute()
{
    return Carbon::parse($this->attributes['birthdate'])->age;
}

然后可以调用age,就好像它是常规属性一样.例如在刀片视图中:

You can then call age as if it was a regular attribute. For example in a blade view:

<p>{{ $user->age }} years</p>

这篇关于使用Laravel 5.2从Y-m-d中存储在数据库中的日期开始计算年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆