簡體   English   中英

如何訪問laravel查詢結果中的列

[英]How to access a column in laravel query result

我的控制器Undefined property: Illuminate\\Database\\Eloquent\\Collection::$created_at出現錯誤Undefined property: Illuminate\\Database\\Eloquent\\Collection::$created_at

如何從laravel查詢的結果中訪問created_at列?

控制器代碼:

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

它適用於findOrFail(some_id)但不適用於此,為什么?

get()返回集合,因此您需要迭代它:

foreach ($posts as $post) {
    echo $post->created_at;
}

或者您可以使用first()來獲取對象而不是集合。 在這種情況下,這將工作:

$post = Post::latest()->first();
$post->created_at;

此外,您不需要將created_at傳遞給latest() ,因為此列被定義為默認值:

public function latest($column = 'created_at')

由於$post是一個實例Collection你必須使用foreach作為:

foreach ($posts as $post) {
    dd($post->created_at);
}

或者您可以first使用first一個對象或last來獲取最后一個對象

dd($posts->first()->created_at);

dd($posts->last()->created_at);

更新

試試看:

foreach ($posts as $post) {
    $post->diff_for_humans = $post->created_at->diffForHumans();
}

然后您可以訪問它:

foreach ($posts as $post) {
    dd($post->diff_for_humans);
}

當你調用get()你可以傳遞一個字段數組來選擇:

$posts = Post::latest()->get(['created_at']);

然后轉儲看看里面有什么dd($post)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM