laravel 5.2 - Model::all() order by

2020-05-31 08:57发布

I get the full collection of a Model with the following:

$posts = Post::all();

However I want this is reverse chronological order.

What is the best way to get this collection in the desired order?

3条回答
forever°为你锁心
2楼-- · 2020-05-31 09:21
$posts = Post::orderBy('created_at', 'desc')->get();

You can use the orderBy method. Replace the column name with the one you want.

查看更多
在下西门庆
3楼-- · 2020-05-31 09:26

You can now use sortBy or sortByDesc:

$posts = Post::all()->sortBy('created_at');
查看更多
来,给爷笑一个
4楼-- · 2020-05-31 09:30

As many may be moving to newer versions of Laravel, you can use ::latest() starting in 5.3 - https://laravel.com/docs/5.5/queries#ordering-grouping-limit-and-offset .

查看更多
登录 后发表回答