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.
Jan 24, 2018
2
Level 1
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?
Level 51
1 like
Please or to participate in this conversation.