Laravel 7-分页按DESC排序



我正试图显示数据库中的帖子,但我想把最新的放在上面。这意味着我必须在我的HomeController.php中执行此操作:

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

但是当网站长大后,找到特定的帖子可能会很复杂,所以我决定实现分页。不幸的是,只有当我使用以下语句时,分页才有效:

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

当我尝试做这样的事情时:

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

我的网站会抛出一个错误,无论我用什么语句来显示反向帖子并对其进行分页。请帮帮我,感谢你们的每一次回应。

您可以使用orderBy并传递"DESC"以降序排列结果。

$posts = Post::orderBy('id', 'DESC')->paginate(10);

Eloquent有一个"最新的";方法应该会有所帮助。https://laravel.com/docs/7.x/queries#ordering-分组限制和偏移

最新更新