Model
protected $fillable=['title','post_at'];
protected $dates=['post_at'];
//日期格式化
public function setPostAtAttribute($date)
{
$this->attributes['post_at']=Carbon::createFromFormat('Y-m-d',$date);
}
public function author()
{
return $this->belongsTo(User::class,'author_id');
}
时区设置:config/app.php:
'timezone' => 'PRC',
小于当前日期的不显示:
$posts=Post::where('post_at','<',Carbon::now())->paginate(5);
return view('posts.index',compact('posts'));
显示某某时间前,如5小时之前
{{$post->post_at->diffForHumans()}}
还要修改app/Providers/AppServiceProvider.php,以显示中文:
use Carbon\Carbon;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Carbon::setLocale('zh');
}

本文详细介绍了在Laravel框架中如何使用模型处理日期和时间,包括设置可填充字段、日期字段格式化、关联作者、时区配置、过滤未发布文章及人性化显示时间间隔的方法。
1088

被折叠的 条评论
为什么被折叠?



