嗨用户通过存储在数据库中的表单添加他们的DOB,
我想计算数据库中存储日期的年龄,格式为Y-m-d,
我的问题是:
这是控制器:
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 getAgeAttribute()
{
return Carbon::parse($this->attributes['birthdate'])->age;
}
然后,您可以将age
称为常规属性。例如,在刀片视图中:
<p>{{ $user->age }} years</p>
要直接显示在您的视图中:
\Carbon\Carbon::parse($user->birth)->diff(\Carbon\Carbon::now())->format('%y years, %m months and %d days');
计算Laravel中的年龄最好使用Carbon in build。在Laravel中返回的日期已经是Carbon格式。
此逻辑应作为模型的默认getter进入模型。
public function getAge(){
$this->birthdate->diff(Carbon::now())
->format('%y years, %m months and %d days');
}
这将导致“23年,6个月和26天”
查看http://carbon.nesbot.com/docs/文档,了解您可以使用它做的所有有趣的事情。
假设您在视图中使用模型,因为您应该在该模型中创建getAge()
函数。
您可以在视图中将模型称为$user->getAge()
谢谢你的所有建议。
碳很容易和令人敬畏。
我在模型中添加了这段代码:
public function age() {
return $this->dob->diffInYears(\Carbon::now());
}
我还设法在视图中将'd-m-Y'中的日期格式'Y-m-d'从数据库更改为传递日期。
我将此代码放在模型中
public function getDOB(){
return $this->dob->format('d-m-Y');
}