random — コレクションからランダム取得
collection
- カテゴリ: collection
- 掲載バージョン: Laravel 12・PHP 8.4
- 名前空間 / FQCN:
Illuminate\Support\Collection::random
- 関連: shuffle, take, first, sample
- 変更履歴: 既存メソッド(挙動の大きな変更なし)
要点(TL;DR)
- コレクションから ランダムに1件または複数件 を取得する
- 例:
$item = collect([1,2,3])->random();
- 罠:
- 件数指定が要素数超過だと 例外
- 1件取得時は Collectionではなく値 が返る
- LazyCollection非対応
概要
random() は、コレクション内の要素をランダムに取得するためのメソッドです。
UIのおすすめ表示、テストデータ抽出、サンプル取得など、順序に意味を持たせたくない場面で使います。
構文 / シグネチャ
random(int $number = null): mixed
引数
| 引数 | 型 | 必須 | 既定値 | 説明 |
|---|
| $number | int | 任意 | null | 取得する件数 |
- 戻り値
$number 未指定: 要素そのもの(mixed)
$number 指定: Collection
- 例外/副作用
- 要素数 <
$number の場合 InvalidArgumentException
使用例
最小例
use Illuminate\Support\Collection;
$col = collect(['apple', 'banana', 'orange']);
$item = $col->random(); // string
複数件取得
$items = $col->random(2); // Collection
実務例(おすすめ記事を3件表示)
use App\Models\Post;
$posts = Post::query()
->where('published', true)
->get()
->random(3);
よくある落とし穴・注意
- 戻り値の型に注意
$col->random(); // 値 $col->random(1); // Collection
- 件数超過は例外
collect([1,2])->random(3); // 例外
- LazyCollectionでは使えない
- 必要なら
->collect()->random() に変換
代替・関連APIとの比較
| メソッド | 特徴 | 選定基準 |
|---|
| random | 完全ランダム | 単発・抽出 |
| shuffle | 全体をシャッフル | 並び替えたい |
| take | 先頭から取得 | 順序重視 |
| sample | 統計的サンプリング | 大量データ |
テスト例(Pest)
it('returns random item', function () {
$col = collect([1, 2, 3]);
$item = $col->random();
expect($col)->toContain($item);
});
トラブルシュート(エラー別)
| 症状/エラー | 原因 | 対処 |
|---|
| InvalidArgumentException | 件数超過 | 件数を制限 |
| 型エラー | 1件取得で値が返る | (array) や random(1)->first() |
参考リンク