LoginSignup
2
2

More than 3 years have passed since last update.

【Laravel】Collectionのrejectメソッド

Posted at

はじめに

今回もLaravelのCollectionのメソッドについてまとめたいと思います。

rejectメソッドで条件に合わないものを除外してデータ取得する

Collectionの中から条件に合わないものを除外してデータ取得することができます。

$collection = collect([
    ['id' => 1, 'name' => '山田', 'age' => 18],
    ['id' => 2, 'name' => '佐藤', 'age' => 38],
    ['id' => 3, 'name' => '小林', 'age' => 25],
    ['id' => 4, 'name' => '鈴木', 'age' => 34],
    ['id' => 5, 'name' => '田中', 'age' => 29],
]);

$filtered = $collection->reject(function($values, $key){

    return ($values['age'] < 30);

});
print_r($filtered->toArray());

実行結果は下記になります。

Array
(
    [1] => Array
        (
            [id] => 2
            [name] => 佐藤
            [age] => 38
        )

    [2] => Array
        (
            [id] => 4
            [name] => 鈴木
            [age] => 34
        )

)

※条件式がtrueになるものは除外さます。

おわりに

いかがでしたでしょうか。
rejectメソッドで条件に当てはまるものを除外できるので試してみてください。

2
2
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
2
2