By default Laravel return eloquent collection. The laravel collection methods are very simple and simple. you can use laraval collection methods and filter data accordingly. Laravel Collections contains many useful and powerful methods that help to filter records.
When you apply helper methods on eloquent collections. It does not run query the database. Get all the results from the database. Then you use Laravel collection methods to filter and modify them without running any query to the database.
In this laravel collection methods tutorial, we will discuss Laravel eloquent collection methods and their uses with simple and easy examples.
18+ Laravel Eloquent Collection Method Example
You can see below 18+ laravel eloquent collection method with examples:
- pluck()
- chunk()
- whereNotIn()
- avg()
- first()
- last()
- merge()
- max()
- min()
- filter()
- search()
- sum()
- map()
- every()
- flip()
- forget()
- isEmpty
- isNotEmpty
Pluck()
pluck() methods return specific key values in collections :
$collection = collect([
['name' => 'test', 'email' => '[email protected]'],
['name' => 'test1', 'email' => '[email protected]'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// Output (Response)
['test', 'test']
Chunk()
Chunk method is used to split the collection into multiple into array.
$tut = collect([a, b, c, d, e, f, g, h]);
$tut = $tut->chunk(3)->toArray();
// Output (Response)
[
0 => [
0 => a,
1 => b,
2 => c
],
1 => [
3 => d,
4 => e,
5 => f
],
2 => [
6 => g,
7 => h
]
]
whereNotIn()
you can use whereNotIn method to filter the collection by a key value not contained within the given array.
$collection->whereNotIn('product_id', [1, 2]);
The above statement return response leave product_id 1,2. This is just opposite of wherein() method.
avg()
AVG method returns the average value. In this below collection avg method return to average of all numbers.
$avg = collect([10, 20, 50, 30, 40]);
$avg->avg();
//Output (Response)
30
first()
first() method returns the first value of collection.
$first = collect([1, 2, 3, 4, 5]);
$first->first();
// Output (Response)
1
last()
last() method returns the last value of collection. last method, just opposite of first method.
$last = collect([1, 2, 3, 4, 5]);
$last->last();
// Output (Response)
5
merge()
merge() methods is used to merge two or more collection or array.
$collection = collect(['1', '2']);
$merged = $collection->merge(['3', '5']);
$merged->all();
// Output (Response)
[1, 2, 3, 5]
max()
max() method return the maximum value of given collection.
$max= collect(['1', '2', '3', '4', '5', '6']);
$max->max();
// Output (Response)
6
min()
min() methods return the minimum value of given collection.
$min= collect(['1', '2', '3', '4', '5', '6']);
$min->min();
// Output (Response)
1
filter()
filter() methods is used to filter the record from collection.
$collection = collect(['1', '2', '3', '4', '5', '6', '7']);
$filtered = $collection->filter(function ($value, $key) {
return $value > 3;
});
// Output (Response)
[4, 5, 6, 7]
search()
search() method is used to search the collection for a given value. If the value is exist in the collection, return true. If the value does not exist in collection, return false.
$collection = collect(['a', 'b', 'c', 'd', 'e', 'f', 'h']);
$search = $collection->search(d);
// Output (Response)
4
sum()
sum() method is very simple in collection and it is used to sum of the collection values.
$collection = collect(['1', '2', '3', '4', '5', '6', '7']);
$sum = $collection->sum();
// Output (Response)
28
toArray()
toArray() methods is used to convert collection into simple php array()
$collection = collect(['name' => 'test', 'email' => [email protected], 'mobile' => '9876543210']);
$collection->toArray();
// Output (Response)
[
[
'name' => 'test',
'email' => [email protected],
'mobile' => '9876543210'
]
]
map()
The map()
method is one of my favorite one. This method will iterate on a collection and return value to a callback function which will form a new collection. In this callback function, you are free to modify the item and return it.
$products = Product::all(); $newPrices = $products->map(function ($item, $key) { return $item['price'] * 2; }); dd($newPrices); // Result will be Collection {#510 ▼ #items: array:5 [▼ 0 => 699.9 1 => 363.9 2 => 299.98 3 => 1359.98 4 => 599.98 ] }
every()
The every()
method will check every element of the collection for a given condition. For example, for our above collection:
$every = $products->every(function ($item, $key){ return $item['price'] > 100; }); dd($every); // true $every = $products->every(function ($item, $key){ return $item['price'] > 300; }); dd($every); // false
flip()
The flip()
method swap the collection keys with their values. Like below:
$products = collect(['name' => 'Blackberry', 'category' => 'phone']); $flipped = $products->flip(); dd($flipped); Collection {#509 ▼ #items: array:2 [▼ "Blackberry" => "name" "phone" => "category" ] }
forget()
The forget()
method will remove an item from the collection by a given key.
$products = collect(['name' => 'Blackberry', 'category' => 'phone']); $products = $products->forget('category'); dd($products); Collection {#514 ▼ #items: array:1 [▼ "name" => "Blackberry" ] }
isEmpty()
The isEmpty()
method will return true
if the given collection is empty, otherwise it will return false
.
$products = Product::all(); $products->isEmpty(); // false
isNotEmpty()
The isNotEmpty()
method will return true
if the given collection is not empty, otherwise it will return false
.
$products = Product::all(); $products->isNotEmpty(); // true
To read more about Laravel collections methods click here