7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravelのコレクションメソッド「sortBy」でつまずいた話

Posted at

前提

Laravelのコレクションメソッドの1つであるsortByを使った結果をソートしている時につまずいたので、解決法を備忘録として残します。

問題点

  • sortByを使うとコレクション内の並び順は下記のように変更されるのですが、JSON化するともとに戻ってしまう
    •   [0] aaaa
        [1] bbbb
      
    •   [1] bbbb
        [0] aaaa
      

解決法

// valuesメソッドを使い、並び替えた結果をもとに採番し直します
$hoge = $hogeModel->hogehoge()->sortByDesc('priority')->values();

参考

7
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?