Question: How to access a column in laravel query result


How to access a column in laravel query result

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

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->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 to

How to access a column in laravel query result

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

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

foreach ($posts as $post) {

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




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) {
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();

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