Laravel 5.1 - 获取日期的月份和日期(具有不同的变量)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37885165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5.1 - get month and day of date (with different variables)
提问by Diego Cespedes
i have my article resource controller, like this:
我有我的文章资源控制器,如下所示:
public function articles()
{
$articles = Article::OrderBy('id','DESC')->paginate(3);
return view('blog', compact('articles'));
}
I would like to pass two variables to my view, like this:
我想将两个变量传递给我的视图,如下所示:
$day = day of created article
$month = month of created article
return view('blog', compact('articles','day','month'));
But I don't know how to get this data from the database, I can get the date of creation like this :
但我不知道如何从数据库中获取这些数据,我可以像这样获取创建日期:
$article->created_at
How can I get only the day and the month to pass to my view?
我怎样才能只将日期和月份传递给我的视图?
回答by Chris Forrence
By default, created_at
is cast to a Carbon instance (reference). Because of that, you can get the day and month attributes directly from the property!
默认情况下,created_at
转换为 Carbon 实例(参考)。因此,您可以直接从属性中获取日和月属性!
@foreach($articles as $article)
{{ $article->created_at->day }}
{{ $article->created_at->month }}
@endforeach
回答by Drown
The created_at
attribute should be a datetime in Laravel.
该created_at
属性应该是 Laravel 中的日期时间。
To get the day and month from it, you can do this :
要从中获取日期和月份,您可以这样做:
$day = date('d', strtotime($article->created_at));
$month = date('m', strtotime($article->created_at));