Laravel 8: Method Illuminate\Database\Eloquent\Collection::latest does not exist

Viewed 6584

I'm working with Laravel 8 to develop my project, and in this project, I have made this method to return latest data from the DB, limiting 5 results:

public function index()
    {
        $posts = Blog::all()->latest()->limit(5);;
        return view('blog', compact('posts'));
    }

As you can see I have used latest() because, I'm using Laravel timestamps (created_at, updated_at) and as this link is saying, there's a handy eloquent/qb method called ->latest() for showing the latest results.

But now I get this as error:

BadMethodCallException Method Illuminate\Database\Eloquent\Collection::latest does not exist.

So what's going wrong here? How can I fix this issue?

I would really appreciate any idea or suggestion from you guys...

Thanks in advance.

Note that I also used Illuminate\Support\Facades\DB; at the top of Controller, but didn't solve the problem!

1 Answers

latest() is a Eloquent\Builder method. Blog::all() is an Eloquent\Collection instance.

For your code to work, it should be:

Blog::latest()->limit(5)->get();
Related