Question: How to access a column in laravel query result

Question

How to access a column in laravel query result

Answers 3
Added at 2016-12-29 14:12
Tags
Question

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?

Answers
nr: #1 dodano: 2016-12-29 14:12

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);
}
nr: #2 dodano: 2016-12-29 14:12

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')
nr: #3 dodano: 2016-12-29 14:12

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)

Source Show
◀ Wstecz