Laravel Collection Helper Cheat Sheet
This article provides a comprehensive cheat sheet of Laravel's Collection helper methods, illustrating how to create, manipulate, and query collections with numerous code examples covering operations such as chunking, merging, filtering, sorting, and converting collections to arrays or JSON.
Laravel's Collection class offers a fluent, convenient wrapper around arrays, enabling powerful data manipulation through a rich set of methods. The following cheat sheet lists common operations with example code.
collect([1, 2, 3]); // create a collectionRetrieve the underlying array:
$collection->all();Calculate the average of items:
collect([1, 1, 2, 4])->avg(); // returns 2Chunk the collection into smaller groups:
collect([1, 2, 3, 4, 5])->chunk(2); // [[1,2], [3,4], [5]]Collapse nested arrays into a single collection:
collect([[1], [4, 5]])->collapse(); // [1, 4, 5]Combine two arrays into a key/value collection:
collect(['name', 'age'])->combine(['George', 29]);Append items to the end of a collection:
collect(['PHP'])->concat(['Laravel']); // ['PHP', 'Laravel']Check if a collection contains a given value:
collect(['name' => 'Desk'])->contains('Desk'); // trueFilter a collection using a callback:
$filtered = $collection->filter(function ($item) { return $item > 2; });Map each item to a new value:
$multiplied = $collection->map(function ($item) { return $item * 2; });Sort the collection by a given key:
$sorted = $collection->sortBy('price');Convert the collection to JSON or a plain array:
$json = $collection->toJson();
$array = $collection->toArray();Additional useful methods include pluck , first , last , push , pop , shift , unshift , unique , values , zip , and many others, each enabling concise and readable data handling within Laravel applications.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.