使用 laravel 5.2 eloquent query & carbon 获取日期并转换格式

Fetch date and convert format using laravel 5.2 eloquent query & carbon

我有控制器代码,它从 table 获取一些行并将它们传递给视图,下面是代码

获取的示例结果

在上图中你可以检查有 show_date 并且格式是 Y-m-d,现在我在视图中显示这个日期,但是我想把这个日期格式转换成这样

 21 Sep 2016 ,Wed

我的控制器代码是

 public function show($id)
{
    $cities=General_cities::pluck('city_name','city_id');
    $showtime=Movies_showtimes::with('showdata','movie','cinema')->where([['cinema_id','=',$id],['show_date','>=',Carbon::today()],])->orderBy('show_date', 'asc')->get();

    $cinemahall=Movies_cinemahall::where('cinema_id',$id)->get();
    return view('admin.viewshowtime',compact('cities','showtime','cinemahall'));
}

我有点困惑如何批量更新 eloquent 对象的所有 show_date 即它应该在获取 eloquent 对象之后完成或者它应该直接在数据库查询中触发或者最好在视图中隐藏日期。

感谢帮助。

$dt = Carbon::today();
echo $dt->format('j F Y \, l'); 

虽然有很多方法,但我认为使用 Carbon 的 format()view 中处理是一个不错的解决方案。请参阅 Carbon docs 了解更多格式化方法。

在遍历您的集合时,您可以将 show_date 格式化为:

$showTime->show_date->format('j M Y, D');

注意:要使其正常工作,show_date 必须是 Carbon 的一个实例。您可以通过在 model 中添加它来告诉 Eloquent 自动执行此操作。它看起来像这样:

/**
 * The attributes that should be mutated to dates.
 *
 * @var array
 */
protected $dates = ['created_at', 'updated_at', 'show_date'];

这是对这个问题有效的最终答案,感谢@camelCase 和@Borna 找出了这个答案的解决方案。

我为此解决方案使用了 Laravel 5.2 访问器,请在此处查看 https://laravel.com/docs/5.3/eloquent-mutators#defining-an-accessor

这是我在模型中编写的访问器代码,它转换在 eloquent 集合中获取的日期格式。

 public function getShowdateAttribute($value)
{
    $carbon = new Carbon($value);
    return $carbon->format('j M Y, D'); 
}