Laravel Collection and Common Collection Methods
Laravel collection is a powerful and versatile feature
provided by Laravel to work with arrays and other data sets. They are
essentially wrappers around arrays with added functionality and methods to make
data manipulation more convenient and expressive. Laravel model and query
builder return collection as default. In this blog we will try to go through
laravel collection and its related methods. There are several methods such as filter(),
chunk(), map(), avg etc.
Here are some key points about Laravel collections for
knowing:
Creating Collections
We can create a collection in Laravel by using the collect
helper function:
$collection = collect([1, 2, 3, 4, 5]);
Laravel query return collection also. You can use below methods on your collections. Here $users variable is a collection
$users = User::all(); $users = User::orderBy('name','asc')->get(); $users = DB::table('users')->orderBy('name','asc')->get();
Common Methods
Laravel collections come with a wide variety of methods for different operations. Those methods have some specific usage and use cases. We can use these methods to deal with our collection data. Here are some commonly used ones:
all(): Get the underlying array.
$array = $collection->all();
avg(): Get the average value of a given key.
$average = $collection->avg();
chunk(): Break the collection into multiple, smaller collections of a given size.
$chunks = $collection->chunk(2);
concat(): Append an array or values of another collection to the collection.
$collection = collect([1, 2, 3]); $concatenated = $collection->concat([4, 5, 6]);
contains(): Determine if the collection contains a given item.
$contains = $collection->contains(3); // true
count(): Get the number of items in the collection.
$count = $collection->count();
filter(): Filter the collection using a callback.
$filtered = $collection->filter(function ($value, $key) { return $value > 2; });
first(): Get the first item in the collection.
$first = $collection->first();
map(): Apply a callback to each item in the collection.
$mapped = $collection->map(function ($item, $key) { return $item * 2; });
pluck(): Retrieve an array of values for a given key.
$collection = collect([ ['name' => 'Desk', 'price' => 200], ['name' => 'Chair', 'price' => 100], ]); $plucked = $collection->pluck('name');
reduce(): Reduce the collection to a single value by iteratively passing each item to a callback.
$total = $collection->reduce (function ($carry, $item) { return $carry + $item; });
sortBy(): Sort the collection by the given key.
$sorted = $collection->sortBy('price');
toArray(): Convert the collection to a plain PHP array.
$array = $collection->toArray ();
Example Usage
Here is a practical example demonstrating the use of several collection methods:
$users = collect([ ['name' => 'Alice','age' => 30], ['name' => 'Bob', 'age' => 25], ['name' => 'Charlie', 'age' => 35], ]);
// Filtering users older than 30
$filtered = $users->filter(function ($user) { return $user['age'] > 30; });
// Plucking names
$names = $users->pluck('name');
// Sorting by age
$sorted = $users->sortBy('age');
// Mapping to get a list of user names
$names = $users->map (function ($user) { return $user['name']; });
// Reducing to get the total age
$totalAge = $users->reduce (function ($carry, $user) { return $carry + $user['age']; }, 0);
Hope that, this blog will help you more to understand laravel collection. Do practice with different collection and try to use above methods, see the outputs