- Laravel Collection methods are:
- pluck()
- chunk()
- whereNotIn()
- avg()
- first()
- last()
- merge()
- max()
- min()
- filter()
- search()
- sum()
- map()
- every()
- flip()
- forget()
- isEmpty
isNotEmpty
How to filter null values from the array in Laravel?
How to calculate average value of array in Laravel?
How to create array in batch sizes in Laravel?
How to flattern multi-dimentional to single array in Laravel?
How to combine two array with key/value pair in Laravel?
How to check if value in array meet given criteria in Laravel?
How to perform multiple operations on array in Laravel?
Pluck()
$collection = collect([
['name' => 'test', 'email' => 'test@gmail.com'],
['name' => 'test1', 'email' => 'test1@gmail.com'],
]);
$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()
We 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' => test@gmail.com, 'mobile' => '9876543210']);
$collection->toArray();
// Output (Response)
[
[
'name' => 'test',
'email' => test@gmail.com,
'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
How to filter null values from the array in Laravel?
// returns object of type Illuminate\Support\Collection
$collection = collect(['sandip', 'chintu', null]);
// loop through collection make all values uppercase
// use reject function reject array values that are empty
$array = $collection
->map(function ($value) {
return Str::upper($value);
})
->reject(function ($name) {
return empty($name);
})->toArray();
// print the array
dd($array);
How to calculate average value of array in Laravel?
// create array to laravel collection object
$collection = collect([
['foo' => 10],
['foo' => 10],
['foo' => 20],
['foo' => 40]
]);
// print average of the collection array
dd($collection->avg());
// OUTPUT: 20
How to create array in batch sizes in Laravel?
// create array to laravel collection object
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
// create array in batch of 5
$batches = $collection->chunk(5);
// display array with batches
dd($batches->all());
// OUTPUT:
** How to flattern multi-dimentional to single array in Laravel?**
// create multi-dimentional array to laravel collection
$collection = collect([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]);
// flattern all arrays into single
$collapsed = $collection->collapse();
// display single array
dd($collapsed->all());
// OUTPUT: [1, 2, 3, 4, 5, 6, 7, 8, 9]
** How to combine two array with key/value pair in Laravel?**
// create array that will be used as keys to laravel collection object
$collection = collect(['name', 'age']);
// supply array that will be used as values
$combined = $collection->combine(['Sandip', 29]);
// display values
dd($combined->all());
// OUTPUT: ['name' => 'Sandip', 'age' => 29]
** How to check if value in array meet given criteria in Laravel?**
// create array to laravel object
$collection = collect([1, 2, 3, 4, 5]);
// check to see if values in array are greater then 5
$moreThenFive =$collection->contains(function ($value, $key) {
return $value > 5;
});
dd($moreThenFive); // OUTPUT: false
// create array to collection object
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
// check to see product has value Table
dd($collection->contains('product', 'Table'));
** How to perform multiple operations on array in Laravel?**
// create employee array to laravel collection
$employees = collect([
['email' => 'james@example.com', 'position' => 'Designer'],
['email' => 'abigail@example.com', 'position' => 'Developer'],
['email' => 'victoria@example.com', 'position' => 'Developer'],
]);
$employees
// find duplicate positions
// with total duplicate counts
->duplicates('position')
// make values uppercase
->map(function ($value) {
return Str::upper($value);
})
// get all values
->all()
// dump given array
->dd();
Latest comments (0)