简体   繁体   中英

How to access a column in laravel query result

I'm getting an error in my controller Undefined property: Illuminate\\Database\\Eloquent\\Collection::$created_at

How can I access a column created_at from a result of laravel query?

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?

get() returns collection, so you need to iterate over it:

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:

$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:

public function latest($column = 'created_at')

As $post is an instance Collection you have to use foreach as:

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

Or you can use first to get first object or last to get last object as

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

when you call get() you can pass an array of fields to select:

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

then dump to see, what is inside with dd($post)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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