LoginSignup
1
0

More than 1 year has passed since last update.

Laravelのコレクション型

Posted at

コレクション型

配列を拡張した型でLaravel独自の型みたいです。
データベースからデータを取得すると、コレクション型になっているみたいです。

関数

コレクション型で使える代表的な関数を一部紹介します。

公式ドキュメント

ここに詳細が載っているので見てください・

chunk

コレクションを指定したサイズで複数の小さなコレクションに分割する関数です。

TestController.php
class TestController extends Controller
{
    
     public function index()
    {
        $values = Test::all(); //Testモデルから取ってくる

        $values = collect([1, 2, 3, 4, 5, 6, 7]);
        $chunks = $values->chunk(4);
        $chunks->all();
        
        // [[1, 2, 3, 4], [5, 6, 7]]

        dd($values);

       return view('tests.test',compact('values'));
       //viewのファイル
     }
}
Illuminate\Support\Collection {#380 ▼
  #items: array:7 [▼
    0 => 1
    1 => 2
    2 => 3
    3 => 4
    4 => 5
    5 => 6
    6 => 7
  ]
}

表示を変えていきます。

TestController.php
class TestController extends Controller
{
    
     public function index()
    {
        $values = Test::all(); //Testモデルから取ってくる

        $values = collect([1, 2, 3, 4, 5, 6, 7]);
        $chunks = $values->chunk(4);
        $chunks->toArray();  //ここを変えた
       
        // [[1, 2, 3, 4], [5, 6, 7]]

        dd($chunks);  //ここを変えた

       return view('tests.test',compact('values'));
       //viewのファイル
     }
}
Illuminate\Support\Collection {#1338 ▼
  #items: array:2 [▼
    0 => Illuminate\Support\Collection {#1339 ▼
      #items: array:4 [▼
        0 => 1
        1 => 2
        2 => 3
        3 => 4
      ]
    }
    1 => Illuminate\Support\Collection {#1337 ▼
      #items: array:3 [▶]
    }
  ]
}

count

コレクションのアイテム数を返します。

TestController.php
class TestController extends Controller
{
    
     public function index()
    {
        $values = Test::all(); //Testモデルから取ってくる
        $values = collect([1, 2, 3, 4,]);
        $values->count();

        dd($values);

       return view('tests.test',compact('values'));
       //viewのファイル
     }
}
lluminate\Support\Collection {#380 ▼
  #items: array:5 [▶]
}

first

指定された真偽テストをパスしたコレクションの最初の要素を返します。

collect([1, 2, 3, 4])->first(function ($value, $key) {
    return $value > 2;
});

// 3
collect([1, 2, 3, 4])->first();

// 1

参考資料

1
0
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
1
0