7

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?

1
  • If that code works with findOrFail then something is wrong. Also, instead of setting Post::created_at in a controller you could use an accessor in your model. Look here Commented Dec 29, 2016 at 13:44

3 Answers 3

8

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')
Sign up to request clarification or add additional context in comments.

4 Comments

will first() return all rows?
No, it will return only one object (first one). If you have multiple items, using foreach is the only option.
It's throwing an error A two digit month could not be found Data missing. Code updated!
@JaskaranSinghPuri it's not related to original question and you should create another question, post the error etc. I think you can't do $post->created_at= and also you don't need to parse created_at since it's already an instance of Carbon.
2

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

2 Comments

Or better yet, call the ->first() method on the query rather than collection itself, if 1 result is all that is needed.
It's throwing an error A two digit month could not be found Data missing. Code updated!
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.