Laravel Collections

Laravel Collection class is a wrapper for working with array. Its like container of array. Laravel also comes with lots of methods which we can perform on collection.

How to create a collection?

Multiple resultsets returned by Eloquent are an example of a collection object. If we have array and we want to use the collection methods then first we need to wrap that array in collection like below and then we can use all Laravel collection methods.

$array = [1,2,3,4,5];
$collection = collect($array);

Some Useful Methods on Laravel Collection

chunk()

The chunk method breaks the collection into multiple, smaller collections of a given size. Often we get a situation where we need to some operation on a large number of data set.

Suppose you have a blog with more then 10 K + posts and you comes in a situation where you need to do some modification to each post. Here is a solution for that you can break all your posts in smaller part and do your logic there.

Post::chunk(200, function ($posts) {
  foreach ($posts as $post) {
    //Logic Comes here
    $post->update();
  }
});

all()

TheĀ all method returns the array represented by the collection.


Leave a Reply

Your email address will not be published. Required fields are marked *