Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

soldenburg's avatar

Formating Date with Carbon in Eloquent Collection

Odd issue, not sure why this isn't working.

In my controller I have a method

$recently_updated = \App\Models\Docs\Page::orderBy('updated_at', 'desc')->take(10)->get();

In my view I then am trying something simple

@foreach ($recently_updated as $page)
    <li>
        <a href="/{{ $page->slug }}">{{ $page->name }}</a>
        <span class="time">{{ $page->updated_at->format('m/d/y') }}</span>
    </li>
@endforeach 

I receive

Call to a member function format() on null (View: /mnt/c/projects/<redacted>/resources/views/index.blade.php)

However, if I go into the controller and

dd($recently_updated[0]->updated_at);

It shows that this should be an instance of Carbon. Similarly I can chain ->format() and get proper results

dd($recently_updated[0]->updated_at->format('m/d/y'); // returns '1/23/18' as expected

Similarly, I can call dd directly in the view to halt execution at the line in question, and it works!

<span class="time">{{ dd($page->updated_at->format('m/d/y')) }}</span>

I can do this, but it feels ugly and wrong.

{{ \Carbon\Carbon::parse($page->updated_at)->format('m/d/y') }}

Am I missing something obvious? What is going on here?

0 likes
2 replies
Talinon's avatar
Talinon
Best Answer
Level 51

Check your database - do any rows in the pages table contain null for created_at? This might explain why it works if you dd() because the first record may have a date, but a subsequent may be null.

1 like
soldenburg's avatar

Should've thought of that. I had a few records entered in the database manually with null dates. Appreciate your help!

Please or to participate in this conversation.