简体   繁体   English

使用laravel 5.2雄辩的查询和Carbon获取日期并转换格式

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

I have controller code which fetches some rows from table and passes those to views, below is the sample result fetched by code 我有控制器代码,该控制器代码从表中获取一些行并将其传递给视图,以下是由代码获取的示例结果

在此处输入图片说明

In above image you can check there is show_date and format is Ymd , Now I am displaying this date in view as it is currently , but i want to convert this date format to something like this 在上面的图像中,您可以检查是否有show_date,格式为Ymd,现在我将其显示为当前日期,但我想将此日期格式转换为如下格式

 21 Sep 2016 ,Wed

My controller code is 我的控制器代码是

 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'));
}

I am little confused how can i update the eloquent object's all show_date in bulk ie It should be done after getting eloquent object or It should be fired directly in db query or Is is better to covert date in View. 我有点困惑,我该如何批量更新雄辩对象的所有show_date,即应该在获得雄辩对象之后执行,还是应该直接在db查询中触发,或者最好在View中隐蔽日期。

Help is appreciated. 感谢帮助。

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

While there are many approaches, I think handling in the view using Carbon's format() is a nice solution. 尽管有很多方法,但我认为使用Carbon的format()view进行处理是一个不错的解决方案。 See the Carbon docs for further formatting methods. 有关更多格式化方法,请参阅Carbon文档

While iterating over your collection, you can format show_date like: 遍历集合时,可以设置show_date格式如下:

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

Note: for this to work, show_date must be a instance of Carbon. 注意:要使其正常工作, show_date必须是Carbon的实例。 You can tell Eloquent to automatically do this by adding it in the model . 您可以通过将Eloquent添加到模型中来告诉Eloquent自动执行此操作。 It would look something like this: 它看起来像这样:

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

This is the final answer which worked for this question, thanks to @camelCase and @Borna for figuring out the solution to this answer. 这是解决该问题的最终答案,这要归功于@camelCase和@Borna找出解决方案。

I used Laravel 5.2 accessor for this solution, check here https://laravel.com/docs/5.3/eloquent-mutators#defining-an-accessor 我将Laravel 5.2访问器用于此解决方案,请在此处查看https://laravel.com/docs/5.3/eloquent-mutators#defining-an-accessor

This is the accessor code that i wrote in Model which converts dateformat fetched in eloquent collection. 这是我在Model中编写的访问器代码,该代码可转换雄辩的集合中获取的dateformat。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM