有一个带有列时间戳的表'评论' 。我希望从创建日期评论的时间差到现在的日期和时间,就像创建的那样' 5天前'有些。我不知道如何从雄辩中做到这一点。 我的控制器是:
public function show($id)
{
$vehicles=vehicles::findorfail($id);
$user=users::where('id',$vehicles->Users_id)->get()->first();
//adding view count
$viewad=ads::where('Vehicleid',$id)->get()->first();
$viewcount=$viewad->views;
$ad = ads::find($viewad->id);
$ad->views=$viewcount+1;
$ad->save();
$comments=comment::where('vehicles_id',$id)->get();
return view('Bike.show',compact('vehicles','user','viewcount','comments'));
}
我怎样才能完成这项任务?谁能告诉我怎么做?
答案 0 :(得分:1)
如果您希望在视图中使用它,最简单的方法是在模型中创建属性访问器。
首先在文件use Carbon\Carbon;
的开头导入Carbon。
然后在Comment
模型中创建属性访问者:
public function getTimeDifferenceAttribute()
{
return $this->time_stamp->diffForHumans(Carbon::now);
}
(我使用snake_case
作为时间戳属性名称,因为您使用的kebab-case
版本在PHP变量名称中无效。)
然后它可以通过评论$comment->time_difference
获得。
编辑:
这个答案假设该模型将time_stamp
视为日期。如果不是这种情况,您还应该将protected $dates = ['time_stamp'];
添加到模型中。
答案 1 :(得分:0)
使用碳。有关详细信息,请参阅Carbon。
$comments=comment::where('vehicles_id',$id)->get();
$today=Carbon::now();
和视图:
@foreach($comments as $comment)
{{$comment->name}} Created {{$today->diffForHumans($comment->time_stamp)}}
@endforeach
您必须导入命名空间才能使用Carbon:
use Carbon\Carbon;