Skip to content
Advertisement

Laravel 7 – paginate sorted by DESC

I’m trying to display posts from the database, but i want to have the latest on top. This means I have to do this inside of my HomeController.php:

$posts = Post::all()->sortByDesc('id');
return view('home', ['posts' => $posts]);

But when the site grows up, it might be complicated to find the particular post, so I decided to implement pagination. Unfortunately, pagination only works when I use this statement:

$posts = Post::paginate(10);
return view('home', ['posts' => $posts]);

When I’m trying to do things like that:

$posts = Post::all()->sortByDesc('id')->paginate(10);

My site throws an error, no matter what statement I use to display reversed posts and paginate them. Please help me and thank you guys for your every response.

Advertisement

Answer

You can use orderBy and pass ‘DESC’ to order the result in descending order.

$posts = Post::orderBy('id', 'DESC')->paginate(10);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement