Quick Summary
Laravel Collections are a powerful feature in the Laravel PHP framework that provides an object-oriented way to work with arrays of data. They wrap around a standard PHP array, offering a rich API of methods for manipulating, filtering, and transforming the data in a more expressive and readable manner. Know more about Laravel collections in this article.
Table of Contents
To filter, sort, or change data, developers spend hours looping over database results. This particular way is time-consuming, and there are huge chances of multiple errors. Laravel Collections reduces this friction.
Collections are simply object-oriented array wrappers. The syntax for common data processing operations is expressive and fluent. Collections use dozens of built-in methods to develop cleaner, more efficient, and scalable code.
Through this article, we will cover the fundamentals of Laravel Collections along with the main methods and their implementations. So, let’s begin…
What are Laravel Collections?
Laravel Collections are improved, object-oriented wrappers around PHP arrays that make working with data easier and expressive. They make it easy for developers to work with arrays or data sets that look like arrays. Collections do this by providing a set of chainable methods that make common tasks, such as sorting, filtering, mapping, reducing, and more, easier.
Basics of Laravel Collections:
- Creation: Collections can be created using the collect() helper, which turns an array into a Collection:
$collection = collect([1, 2, 3]);
- Immutability: Collections cannot be changed. So every time when you call a method on them, you will get a new Collection. The original collection would not change, which is good for productive computing.
- Chaining: Collection methods can be linked together, which lets you do more than one thing on a single line. As an example:
$collection = collect([1, 2, 3])
->map(fn($value) => $value * 2)
->filter(fn($value) => $value > 2);
// Result: [4, 6]
Common Laravel Collection Methods:
- map(): Turns every item in the collection.
- filter(): Filters items based on a callback.
- reduce(): Reduces the collection to a single value.
- pluck(): Extracts a set of values by key.
- sort(), sortBy(): Sorts items by natural order or specific criteria.
- IsEmpty(): If the collection is empty, returns true.
- isNotEmpty(): Returns true if the collection has at least one item.
Collections are “macroable,” which means that coders can add custom methods to them at runtime using the macro() method.
Laravel Collections make it easy and natural to change complex data, which lets developers write code that is cleaner, easier to manage, and faster.
14 Top Laravel Collection Methods
Learning how to use Laravel Collections will let you change data in your projects in a way that is both easy and quick. This carefully chosen list of methods, put together by our professionals, will help you use Collections to improve your development process.
1. Creating Collections
Laravel’s Collection capability makes data management simple and rapid. Collections provide data manipulation, categorization, and organization. This makes them essential for Laravel data management.
(Note: The following methods will be presented with examples. Make sure to check what applies to your needs, i.e., in some cases dd() method would be used, and in some other debugging method.)
- To create an Empty Collection:
$emptyCollection = collect();
- To create a Collection from an Array:
$data = [1, 2, 3, "apple", "banana"];
$collectionFromArray = collect($data);
- To build using make() Method:
$collection = Collection::make([1, 2, 3, 4]);
It is similar to collect(), mostly used internally
- To retrieve results as Collections:
$users = User::all(); // Returns a collection of User models
Collections simplify data processing and application development.
2. Accessing Items
Laravel collections have multiple methods to access and retrieve specific items or information from data sets.
- Get All Items as an Array:
$collection = collect([1, 2, 3]);
$array = $collection->all(); // Returns [1, 2, 3]
- Calculate Average/Mean:
$scores = collect([85, 90, 78, 92]);
$average = $scores->avg(); // Gets 86.25 as answer
- Access First and Last Items:
$collection = collect(['a', 'b', 'c']);
$first = $collection->first(); // Returns 'a'
$last = $collection->last(); // Output 'c'
- Get Item by Key with Default:
$users = collect(['name' => 'John', 'age' => 30]);
$name = $users->get('name', 'Unknown'); // Output would be 'John'
$city = $users->get('city', 'Not specified'); // Returns 'Not specified'
- Extract Values by Key:
$products = collect([
['name' => 'Laptop', 'price' => 1000],
['name' => 'Phone', 'price' => 500]
]);
$prices = $products->pluck('price'); // Returns [1000, 500]
3. Adding/Removing Items
Modify collections by adding or removing elements with these essential methods.
- Add Items to Collection
$collection = collect([1, 2, 3]);
$collection->push(4); // Adds to end: [1, 2, 3, 4]
$collection->prepend(0); // Adds to beginning: [0, 1, 2, 3, 4]
- Remove and Return Items
$collection = collect(['a', 'b', 'c']);
$last = $collection->pop(); // Returns 'c', collection becomes ['a', 'b']
$first = $collection->shift(); // Returns 'a', collection becomes ['b']
- Remove by Key and Set Values
$collection = collect(['name' => 'John', 'age' => 30]);
$collection->forget('age'); // Removes age key
$collection->put('city', 'New York'); // Adds/updates city
4. Filtering and Searching
Powerful filtering and searching capabilities to find and isolate specific data within collections.
- Filter with Custom Logic
$products = collect([
['name' => 'Laptop', 'price' => 1000],
['name' => 'Phone', 'price' => 500],
['name' => 'Tablet', 'price' => 300]
]);
$expensive = $products->filter(function ($product) {
return $product['price'] > 400;
});
- Reject Items (Opposite of Filter)
$cheap = $products->reject(function ($product) {
return $product['price'] > 400;
});
- Where Clauses for Filtering
$activeUsers = $users->where('status', 'active');
$premiumUsers = $users->whereIn('plan', ['premium', 'enterprise']);
$freeUsers = $users->whereNotIn('plan', ['premium', 'enterprise']);
- Find First Matching Item
$admin = $users->firstWhere('role', 'admin');
$searchIndex = $collection->search('value'); // Returns key/index
5. Modifying Collections
To change and modify collection data while maintaining the collection structure.
- Map – (Change Each Item)
$numbers = collect([1, 2, 3, 4]);
$squared = $numbers->map(function ($number) {
return $number * $number;
}); // Returns [1, 4, 9, 16]
- Map with Keys – Custom Key-Value Pairs
$users = collect([
['id' => 1, 'name' => 'John'],
['id' => 2, 'name' => 'Jane']
]);
$mapped = $users->mapWithKeys(function ($user) {
return [$user['id'] => $user['name']];
}); // Returns [1 => 'John', 2 => 'Jane']
- Flat Map – Map and Flatten
$data = collect([
['tags' => ['php', 'laravel']],
['tags' => ['javascript', 'vue']]
]);
$tags = $data->flatMap(function ($item) {
return $item['tags'];
}); // Returns ['php', 'laravel', 'javascript', 'vue']
- Flatten Nested Arrays
$nested = collect([[1, 2], [3, [4, 5]]]);
$flat = $nested->flatten(); // Returns [1, 2, 3, 4, 5]
6. Sorting
Organize collection data with comprehensive sorting methods.
- Basic Sorting
$numbers = collect([3, 1, 4, 1, 5]);
$sorted = $numbers->sort(); // Returns [1, 1, 3, 4, 5]
- Sort by Specific Key
$users = collect([
['name' => 'John', 'age' => 30],
['name' => 'Jane', 'age' => 25]
]);
$sortedByAge = $users->sortBy('age');
$sortedByAgeDesc = $users->sortByDesc('age');
- Sort by Keys and Reverse
$collection = collect(['b' => 2, 'a' => 1, 'c' => 3]);
$sortedKeys = $collection->sortKeys(); // ['a' => 1, 'b' => 2, 'c' => 3]
$reversed = $collection->reverse(); // ['c' => 3, 'a' => 1, 'b' => 2]
7. Reducing / Aggregating
Perform mathematical operations and aggregate data from collections.
- Mathematical Operations
$prices = collect([10.50, 25.00, 15.75]);
$total = $prices->sum(); // Returns 51.25
$average = $prices->avg(); // Returns 17.083333
$min = $prices->min(); // Returns 10.50
$max = $prices->max(); // Returns 25.00
$count = $prices->count(); // Returns 3
- Reduce to a Single Value
$numbers = collect([1, 2, 3, 4]);
$product = $numbers->reduce(function ($carry, $item) {
return $carry * $item;
}, 1); // Returns 24 (1*2*3*4)
8. Grouping
Organize collections by grouping related items together.
- Group by Key or Callback
$users = collect([
['name' => 'John', 'department' => 'IT'],
['name' => 'Jane', 'department' => 'HR'],
['name' => 'Bob', 'department' => 'IT']
]);
$grouped = $users->groupBy('department');
// Returns: ['IT' => [...], 'HR' => [...]]
- Key By Specific Field
$users = collect([
['id' => 1, 'name' => 'John'],
['id' => 2, 'name' => 'Jane']
]);
$keyed = $users->keyBy('id');
// Returns: [1 => ['id' => 1, 'name' => 'John'], 2 => [...]]
9. Chunking / Slicing
Break down collections into smaller, manageable pieces.
- Split into Chunks
$collection = collect([1, 2, 3, 4, 5, 6]);
$chunks = $collection->chunk(2); // Returns [[1, 2], [3, 4], [5, 6]]
- Slice Collection
$slice = $collection->slice(2, 3); // Returns [3, 4, 5] (from index 2, take 3)
- Take and Skip Items
$first3 = $collection->take(3); // Returns [1, 2, 3]
$remaining = $collection->skip(3); // Returns [4, 5, 6]
$takeUntil = $collection->takeUntil(function ($item) {
return $item > 3;
}); // Returns [1, 2, 3]
$takeWhile = $collection->takeWhile(function ($item) {
return $item < 4;
}); // Returns [1, 2, 3]
10. Combining Collections
Merge and combine multiple collections efficiently.
- Merge Collections
$collection1 = collect([1, 2, 3]);
$collection2 = collect([4, 5, 6]);
$merged = $collection1->merge($collection2); // [1, 2, 3, 4, 5, 6]
- Concatenate and Zip
$concat = $collection1->concat($collection2); // Similar to merge
$zipped = $collection1->zip($collection2); // [[1, 4], [2, 5], [3, 6]]
- Union Collections
$colors = collect(['red' => 1, 'green' => 2]);
$fruits = collect(['apple' => 3, 'red' => 4]);
$union = $colors->union($fruits); // Preserves original keys, no overwrite
11. Boolean Checks
Validate collection states and contents with boolean operations.
- Check Collection State
$empty = collect([]);
$filled = collect([1, 2, 3]);
$empty->isEmpty(); // Returns true
$empty->isNotEmpty(); // Returns false
$filled->isEmpty(); // Returns fals
$filled->isNotEmpty(); // Returns true
- Check for Values and Conditions
$numbers = collect([1, 2, 3, 4, 5]);
$numbers->contains(3); // Returns true
$numbers->has(0); // Returns true (key exists)
$numbers->every(function ($item) {
return $item > 0;
}); // Returns true (all positive)
$numbers->some(function ($item) {
return $item > 3;
}); // Returns true (at least one > 3)
12. Iterating
Loop through collections with advanced iteration methods.
- Each Method with Control
$products = collect([
['name' => 'Laptop', 'price' => 1000],
['name' => 'Phone', 'price' => 500]
]);
$products->each(function ($product, $key) {
echo "Product: {$product['name']}, Price: {$product['price']}\n";
// Return false to stop iteration early
});
- Each Spread for Arrays
$coordinates = collect([[1, 2], [3, 4]]);
$coordinates->eachSpread(function ($x, $y) {
echo "Point: ($x, $y)\n";
});
- Pipe for Custom Processing
$result = $collection->pipe(function ($collection) {
return $collection->sum() / $collection->count();
});
13. Converting
Transform collections into different data formats.
- Convert to Array and JSON
$collection = collect(['name' => 'John', 'age' => 30]);
$array = $collection->toArray(); // ['name' => 'John', 'age' => 30]
$json = $collection->toJson(); // '{"name":"John","age":30}'
- JSON Serialization
$collection = collect([1, 2, 3]);
echo json_encode($collection); // Uses jsonSerialize() method
14. Miscellaneous / Advanced Operations
Additional powerful methods for specialized collection operations.
- Remove Duplicates
$collection = collect([1, 2, 2, 3, 3]);
$unique = $collection->unique(); // Returns [1, 2, 3]
$users = collect([
['id' => 1, 'name' => 'John'],
['id' => 2, 'name' => 'John'],
['id' => 3, 'name' => 'Jane']
]);
$uniqueNames = $users->unique('name'); // Unique by name field
- Collapse and Diff Operations
$nested = collect([
[1, 2, 3],
[4, 5, 6]
]);
$collapsed = $nested->collapse(); // Returns [1, 2, 3, 4, 5, 6]
$collection1 = collect([1, 2, 3]);
$collection2 = collect([2, 3, 4]);
$diff = $collection1->diff($collection2); // Returns [1]
$keyDiff = $collection1->diffKeys($collection2); // Compare keys
- String Operations and Utilities
$words = collect(['Hello', 'World', 'Laravel']);
$sentence = $words->implode(' '); // Returns "Hello World Laravel"
$shuffled = $collection->shuffle(); // Random order
- Tap for Debugging (the tap() method)
$result = collect([1, 2, 3, 4])
->tap(function ($collection) {
// Debug or log without breaking the chain
\Log::info('Collection size: ' . $collection->count());
})
->filter(function ($item) {
return $item > 2;
})
->values();
These debugging methods, like var_dump() and caution in your code, can help you find problems early. This enables smooth, reliable application operation. Choose your preferred debugging approach for the desired results.
You may confidently manage and process Laravel data after mastering these basics. Following these practices ensures efficient applications. Remember, these tips are fundamental. Explore our Laravel development company and check out more collection methods to access powerful data management.
5 Most Used Categories of Methods in Laravel Collection
Laravel Collections offer many ways to work with data arrays. This list of common procedures is categorized by their main purpose:
1. Transformation & Manipulation:
- all(): Returns the main array of the collection.
- map(callable $callback): Goes to the items and passes each to a callback, returning a new collection with the changed items.
- mapWithKeys(callable $callback): Same as map, but you can define both the key and value for each item in the new collection.
- flatMap(callable $callback): Maps over the items and flattens the resulting collection of arrays into a single collection.
- transform(callable $callback): Modifies the collection in place by applying a callback to each item.
- pluck(string|array $value, string|null $key = null): Retrieves all of the values for a given key.
- keyBy(string|callable $keyBy): Keys the collection by a given key.
- flip(): Flips the collection’s keys and values.
- reverse(): Reverses the order of the items in the collection.
- shuffle(): Randomly shuffles the items in the collection.
- sort(callable|null $callback = null): Sorts the collection.
- splice(int $offset, int|null $length = null, mixed $replacement = []): Removes and returns a slice of items from the collection.
- chunk(int $size): Breaks the collection into several, smaller collections of a given size.
- split(int $numberOfGroups): Splits a collection into a given number of groups.
- collapse(): Collapses a collection of arrays into a single, flat collection.
- flatten(int $depth = INF): Flattens a multi-dimensional collection into a single dimension.
2. Filtering & Selection:
- filter(callable|null $callback = null): Filters the collection using a given callback.
- reject(callable $callback): Filters out items from the collection using a given callback.
- where(string $key, mixed $operator = null, mixed $value = null): Filters the collection by a given key/value pair.
- whereStrict(string $key, mixed $value): Filters the collection by a given key/value pair using strict comparison.
- whereIn(string $key, array $values, bool $strict = false): Filters the collection by a given key’s presence in an array of values.
- whereNotIn(string $key, array $values, bool $strict = false): Filters the collection by a given key’s absence in an array of values.
- only(array|mixed $keys): Returns a new collection containing only the specified keys.
- except(array|mixed $keys): Returns a new collection containing all items except the specified keys.
- first(callable|null $callback = null, mixed $default = null): Returns the first item in the collection that passes a given truth test.
- last(callable|null $callback = null, mixed $default = null): Returns the last item in the collection that passes a given truth test.
- random(int|null $number = null): Returns a random item or items from the collection.
- forPage(int $page, int $perPage): Returns a new collection containing the items for a given page number.
3. Aggregation & Calculation:
- count(): Returns the total number of items in the collection.
- sum(callable|string|null $callback = null): Returns the sum of all items in the collection, or the sum of values for a given key.
- avg(callable|string|null $callback = null): Returns the average of all items in the collection, or the average of values for a given key.
- median(string|null $key = null): Returns the median of all items in the collection, or the median of values for a given key.
- mode(string|null $key = null): Returns the mode of all items in the collection, or the mode of values for a given key.
- max(string|null $key = null): Returns the maximum value in the collection, or for a given key.
- min(string|null $key = null): Returns the minimum value in the collection, or for a given key.
- reduce(callable $callback, mixed $initialValue = null): Reduces the collection to a single value using a callback.
4. Checking & Comparison:
- contains(mixed $key, mixed $operator = null, mixed $value = null): Checks if the collection contains a given item or key/value pair.
- containsStrict(mixed $key, mixed $value = null): Checks if the collection contains a given item or key/value pair using strict comparison.
- isEmpty(): Determines if the collection is empty.
- isNotEmpty(): Determines if the collection is not empty.
- has(array|string $key): Determines if a given key exists in the collection.
- every(callable $callback): Determines if all items in the collection pass a given truth test.
- diff(array|Collection $items): Compares the collection against another collection or array and returns the values that are not present in the given items.
- diffAssoc(array|Collection $items): Compares the collection against another collection or array and returns the key/value pairs that are not present in the given items.
- diffKeys(array|Collection $items): Compares the collection against another collection or array and returns the key/value pairs whose keys are not present in the given items.
- intersect(array|Collection $items): Returns a new collection containing only the values that are present in both the original collection and the given items.
- intersectKey(array|Collection $items): Returns a new collection containing only the key/value pairs whose keys are present in both the original collection and the given items.
5. Adding & Removing:
- push(mixed $value): Pushes an item onto the end of the collection.
- prepend(mixed $value, mixed $key = null): Prepends an item onto the beginning of the collection.
- put(mixed $key, mixed $value): Puts an item into the collection at a given key.
- forget(array|string $keys): Removes an item or items from the collection by key.
- pull(mixed $key, mixed $default = null): Removes and returns an item from the collection by key.
- pop(): Removes and returns the last item from the collection.
- shift(): Removes and returns the first item from the collection.
- merge(array|Collection $items): Merges the collection with another array or collection.
- union(array|Collection $items): Merges the collection with another array or collection, but only adds keys that are not already present.
- combine(array|Collection $values): Combines the collection’s values with the keys of another array or collection.
- concat(array|Collection $items): Concatenates another array or collection onto the end of the current collection.
Lessons and Key Data Points
Laravel Collections offer a powerful, intuitive, and flexible approach to data manipulation. By providing a wide range of built-in methods, they simplify handling arrays, making your code more readable and maintainable.
Be it filtering, mapping, or chaining complex operations, Collections make working with data easier and more efficient for Laravel developers. Mastering Collections not only enhances your workflow but also unlocks the full potential of Laravel’s data-handling capabilities. So, dive in, experiment, and make the most out of Laravel Collections in your projects!
If you need professional assistance, hire Laravel developers for your project!
FAQs on Laravel Collections
What is the difference between a collection and an array in Laravel?
Object-oriented collections surround arrays with data manipulation techniques. Although arrays are basic data structures, collections offer more capabilities and chainable syntax.
How to merge two collections in Laravel?
To merge two Laravel collections, use the merge() method:
$merged = $collection1->merge($collection2);
Why you should use Laravel collections instead of PHP arrays?
You should use Laravel collections instead of PHP arrays because they offer more methods, better readability, and chainable operations, making data handling simpler and code more maintainable.
How do I know if a Laravel collection is empty?
To know if a Laravel collection is empty, use the isEmpty() method:
$collection->isEmpty();
How to order a Collection in Laravel?
To order a Collection in Laravel, use sort() for natural sorting or sortBy(‘key’) for sorting by a specific key.
What is the difference between fluent and collection in Laravel?
Fluent is simple and provides direct property access, while Collection handles sophisticated data processing. Also, Fluent has a key/value storage interface, but Collections has hundreds of methods like map, filter, and reduce.
Boost Your Data Skills with Laravel Collections
Master Laravel Collections to handle data effortlessly. We have the best methods, categories, and techniques to simplify manipulation and supercharge your Laravel projects.