laravel 如何访问laravel查询结果中的一列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41380781/
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
How to access a column in laravel query result
提问by Jaskaran Singh Puri
I'm getting an error in my controller Undefined property: Illuminate\Database\Eloquent\Collection::$created_at
我的控制器出现错误 Undefined property: Illuminate\Database\Eloquent\Collection::$created_at
How can I access a column created_at
from a result of laravel query?
如何created_at
从 Laravel 查询的结果访问列?
Controller Code:
控制器代码:
public function getDashboard() {
$posts=Post::latest('created_at')->get();
dd($posts->created_at);
// $posts->created_at=Carbon::parse($posts->created_at)->diffForHumans(Carbon::now());
return view('dashboard',compact('posts'));
}
It works with findOrFail(some_id)
but not with this, why?
它适用于findOrFail(some_id)
但不适用于此,为什么?
采纳答案by Alexey Mezenin
get()
returns collection, so you need to iterate over it:
get()
返回集合,因此您需要对其进行迭代:
foreach ($posts as $post) {
echo $post->created_at;
}
Or you could use first()
to get object instead of collection. In this case this would work:
或者您可以使用first()
获取对象而不是集合。在这种情况下,这将起作用:
$post = Post::latest()->first();
$post->created_at;
Also, you don't need to pass created_at
to latest()
, because this column is defined as default:
此外,您不需要传递created_at
给latest()
,因为此列已定义为默认值:
public function latest($column = 'created_at')
回答by Amit Gupta
As $post
is an instance Collection
you have to use foreach
as:
作为$post
一个实例,Collection
您必须foreach
用作:
foreach ($posts as $post) {
dd($post->created_at);
}
Or you can use first
to get first object or last
to get last object as
或者您可以使用first
获取第一个对象或last
获取最后一个对象作为
dd($posts->first()->created_at);
dd($posts->last()->created_at);
Update
更新
Try it as:
试试看:
foreach ($posts as $post) {
$post->diff_for_humans = $post->created_at->diffForHumans();
}
Then your can access it as:
然后你可以访问它:
foreach ($posts as $post) {
dd($post->diff_for_humans);
}
回答by meda
when you call get()
you can pass an array of fields to select:
当你打电话时,get()
你可以传递一个字段数组来选择:
$posts = Post::latest()->get(['created_at']);
then dump to see, what is inside with dd($post)
然后转储看看,里面有什么 dd($post)