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

NoneNameDeveloper's avatar

Call to a member function format() with date | Laravel 5.6

After working with Laravel 5.6.x i have some errors with date to string. In older versions i used it for date to string.

{{ $blogs->created_at->format('Y-m-d , G:i:s') }}

But after laravel 5.6 it doesn't work. How can i fix it? Thanks!

0 likes
6 replies
Snapey's avatar

It still works.

Is $blogs a single model or is it a collection of models?

NoneNameDeveloper's avatar

@Snapey thanks, But I have all is same with older version of Laravel. So I have this controller.

public function index()
{
   $blogs = DB::table('blogs')
                       ->leftJoin('blog_categories', 'blogs .cat_id', '=', blog_categories.id')
                       ->select('blogs .*','blog_categories.category_name')
                       ->where(array('featured_blog'=>'1'))->take(6)->get();
    return view('pages.home',compact('categories', blogs));
}
And in view

@foreach(blogs as blog) {{ $blogs->created_at->format('Y-m-d , G:i:s') }} @endforeach.

Cronix's avatar

$blog->created_at, not $blogs...

@foreach($blogs as $blog)
    {{ $blog->created_at->format('Y-m-d , G:i:s') }}
@endforeach 
ninoman's avatar
ninoman
Best Answer
Level 1

You are getting blogs by DB facade, which returns a collection of /stdClass instances and of course $blog->created_at is just a string, so you can't call format method on it. You should parse it to Carbon, or get your blogs using Blog model.

Cronix's avatar

Ah, missed that @ninoman and you're correct. It really would be best as an eloquent model with relationships, but if not...

@foreach($blogs as $blog)
    {{ Carbon\Carbon::parse($blog->created_at)->format('Y-m-d , G:i:s') }}
@endforeach 

If you were using an eloquent model, created_at is automatically converted to a carbon instance. It's not if using DB.

2 likes

Please or to participate in this conversation.