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 Tech Community
Laravel Tech Community
Laravel Tech Community
Laravel Collection Helper Cheat Sheet

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 collection Retrieve the underlying array: $collection->all(); Calculate the average of items: collect([1, 1, 2, 4])->avg(); // returns 2 Chunk 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'); // true

Filter 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPCollectionsLaravelHelper
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.