- カテゴリ: collection
 - 掲載バージョン: Laravel 12・PHP 8.4
 - 名前空間 / FQCN / コマンド: 
Illuminate\Support\Collection::sort - 関連: sortDesc / sortBy / sortByDesc / sortKeys / sortKeysDesc
 - 変更履歴: 主要な仕様変更なし(Laravel 8+ 同等)
 
要点(TL;DR)
- 値で昇順ソート。キーは保持、元コレクションは変化しない。
 - 最低限の使い方:
$sorted = collect([3,1,2])->sort(); - 罠:比較関数の戻り値はintにする/大規模データはDBで orderBy/文字列比較はASCII順で自然順・ロケールではない。
 
概要
sort はコレクションの値を昇順に整列します。コールバックを渡すと PHP の uasort 相当の比較ができます。キーは保持され、元のコレクションは変更されません。降順やフィールド基準の整列は sortDesc / sortBy を選びます。
構文 / シグネチャ
/**** Laravel 12 ****/
public function sort(callable|null $callback = null): static;
- 引数(表)
 
| 引数 | 型 | 必須 | 既定値 | 説明 | 
|---|---|---|---|---|
$callback | `callable | null` | null | 
- 戻り値:
Collection(新インスタンス、キー保持) - 例外/副作用:無効なコールバックで 
TypeError。コールバック内例外はそのまま伝播。ソートは安定保証なし。 
(collection特性)
- チェーン可 / 非破壊 / キー保持
 - LazyCollection:呼び出すと全件をメモリ展開してから並び替え(巨大データには不向き)
 - 計算量目安:O(n log n)
 
入出力対応(サンプル)
| 入力 | 呼び出し | 出力 | 
|---|---|---|
collect(['b','a']) | ->sort() | ['a','b'](キー保持) | 
collect([10=>'b',5=>'a']) | ->sort() | [5=>'a',10=>'b'] | 
使用例
最小例
use Illuminate\Support\Collection;
$sorted = collect([3, 1, 2])->sort();
// $sorted: [1, 2, 3](キー保持)
実務例:日本語名の比較を安定させたい(Collator 使用)
use Illuminate\Support\Collection;
use Collator;
$users = collect([
    ['id' => 1, 'name' => 'あおき'],
    ['id' => 2, 'name' => 'アオキ'],
    ['id' => 3, 'name' => '青木'],
]);
$collator = new Collator('ja_JP');
$sorted = $users->sort(fn ($a, $b) => $collator->compare($a['name'], $b['name']));
実務例:複合条件(数値優先→同点は文字列)
use Illuminate\Support\Collection;
$items = collect([
    ['score' => 90, 'name' => 'C'],
    ['score' => 90, 'name' => 'A'],
    ['score' => 70, 'name' => 'B'],
]);
$sorted = $items->sort(function ($a, $b) {
    return ($a['score'] <=> $b['score'])   // まず score 昇順
        ?: strcmp($a['name'], $b['name']); // 同点なら名前で
});
DBで並び替えられるなら:Eloquent/QueryBuilder の
orderByを使う方が高速・省メモリ。
よくある落とし穴・注意
- 比較関数は int を返す:
true/falseを返すと不定な順序になりやすい。<=>やstrcmpを使う。 - 文字列の既定比較は ASCII 順:自然順(
"a2"<"a10"問題)やロケール準拠は自前で。sortBy(..., SORT_NATURAL)やCollatorを検討。 - 大規模データは不向き:全件をメモリに載せてソート。DB の 
orderByや ストリーミング前提の再設計を。 - 安定ソートではない:同値要素の相対順は保証しない。必要ならキー付与・二段階ソートなどを検討。
 - 降順は 
sortDesc、フィールド基準はsortByを使う方が簡潔。 
代替・関連APIとの比較
sort:値ベースの昇順、キー保持・非破壊。比較関数で柔軟。sortDesc:降順。sortBy($callback, $options=SORT_REGULAR, $descending=false):プロパティ/キー指定やSORT_NATURAL等のフラグが使える。sortKeys/sortKeysDesc:キーで並び替え。
選定基準:フィールド基準や自然順が必要→sortBy。単純に値だけ→sort。
テスト例(Pest)
use Illuminate\Support\Collection;
it('sorts values ascending and keeps keys', function () {
    $c = collect([10 => 'b', 5 => 'a']);
    expect($c->sort()->all())->toBe([5 => 'a', 10 => 'b']);
});
it('sorts with comparator', function () {
    $c = collect([['n' => 2], ['n' => 1]]);
    $sorted = $c->sort(fn($a, $b) => $a['n'] <=> $b['n']);
    expect($sorted->pluck('n')->all())->toBe([1, 2]);
});
トラブルシュート(エラー別)
| 症状/エラー | 原因 | 対処 | 
|---|---|---|
| 並びが不安定・期待通りでない | 比較関数が bool を返す/同値の順序未定 | -1/0/1 を返す。<=>/strcmp を使う。必要ならキー追加で安定化。 | 
| 文字列の順序が想定と違う | 既定は ASCII 比較 | sortBy(..., SORT_NATURAL) か Collator('ja_JP') を使用。 | 
| メモリ不足 | 全件メモリ展開+ソート | DB の orderBy へ委譲/件数を絞る/ページング。 | 
| 降順にしたい | sort は昇順のみ | sortDesc() を使用。 | 
参考リンク
- Laravel Docs: Collections — Sorting(sort, sortBy, etc.)
https://laravel.com/docs/12.x/collections#method-sort - Laravel API: 
Illuminate\Support\Collection::sort(ソース)
https://github.com/laravel/framework/blob/12.x/src/Illuminate/Support/Collection.php - PHP Manual: 
asort/uasort(比較とキー保持)
https://www.php.net/asort
https://www.php.net/uasort - PHP Manual: Collator(国際化ソート、ext-intl)
https://www.php.net/collator 

  
  
  
  