嗨,用户通过存储在数据库中的表单添加他们的 DOB,
我想根据数据库中存储的日期计算年龄,格式为 Y-m-d,
我的问题是:
如何计算年龄?
逻辑放在哪里, Controller 还是模型?
如何以“m-d-Y”格式在 View 中传递存储的日期
如何传递 View 中年龄的逻辑结果。
我在我的模型中使用了如下内容,对吗?
这是 Controller :
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>
这样对吗?我收到如下错误
Call to a member function diff() on null
最佳答案
日期可以是 Carbon 的实例,它提供了各种有用的方法。
在您的模型中,导入 Carbon 类:
use Carbon\Carbon;
并定义一个访问器:
/**
* Accessor for Age.
*/
public function age()
{
return Carbon::parse($this->attributes['birthdate'])->age;
}
然后您可以像调用常规属性一样调用 age
。例如在 Blade View 中:
<p>{{ $user->age() }} years</p>
关于php - 使用 Laravel 5.2 从 Y-m-d 中存储在数据库中的日期计算年龄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35524482/