The collection is one of the most powerful features. Laravel provides you with. If you are unfamiliar with the nature of Laravel collections, you are likely to run into problems when working with Laravel Eloquent. For example, in the simplest case, suppose you have dozens of data that you want to calculate the average of this data, or suppose you have an array of numbers, letters, expiration date, consumer price, and selling price, now without using Collections to calculate the sum Selling one day becomes almost impossible. These are just a few small examples of the collections we will introduce and teach you in this article.
Collection names in Laravel
To date, Laravel contains more than 120 collections with amazing capabilities, which we will first name and then explain each them.
- all
- average
- avg
- chunk
- collapse
- collect
- combine
- contact
- contains
- count
- country
- cross join
- dd
- diff
- diffAssoc
- differs
- dump
- duplicates
- duplicatesStrict
- each
- except
- first
- firstWhere
- flip
- forget
- get
- groupBy
- has
- implode
- intersect
- intersectByKeys
- isEmpty
- is not empty
- join
- last
- max
- median
- merge
- merge-recursive
- min
- pluck
- pop
- prepend
- pull
- push
- put
- random
- replace
- reverse
- search
- shift
- shuffle
- sort
- sortBy
- sortByDesc
- sorties
- sortKeys
- sortKeysDesc
- splice
- sum
- times
- toArray
- unique
- unless
- unwrap
- values
- where
- where strict
- and whereIn
- where instance of
- whereNotBetween
Application of Collections in Laravel
all
This method returns all the data in an array.
collect ([ 1 , 2 , 3 ]) -> all ();
// [1, 2, 3]
average
This method and the avg () method return the average of the data.
$ average = collect ([[ 'foo' => 10 ], [ 'foo' => 10 ], [ 'foo' => 20 ], [ 'foo' => 40 ]]) -> avg ( 'foo' );
// 20
$ average = collect ([ 1 , 1 , 2 , 4 ]) -> average ();
// 2
chunk
This method categorizes an array evenly. For example, if we apply a chunk to an 8 (4). This array is divided into two arrays of 4, but if, for example, the number of array members is 10, the chunk divides it into two arrays of 4 and 1 array of 2.
$ collection = collect ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 ]);
$ chunks = $ collection -> chunk ( 4 );
$ chunks -> toArray ();
// [[1, 2, 3, 4], [5, 6, 7]]
This method is very useful when working with views. We divided the products into three arrays and displayed them in the following example.
@foreach ($ products-> chunk (3) as $ chunk)
< div class = "row" >
@foreach ($ chunk as $ product)
< div class = "col-xs-4" > product {$ product-> name}} </ div >
@endforeach
</ div >
@endforeach
collapse
This method converts several arrays into one array.
$ collection = collect ([[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]]);
$ collapsed = $ collection -> collapse ();
$ collapsed -> all ();
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
collect
This method creates a new Collection from the original Collection, meaning we can use this method when we want to copy a Collection.
$ collectionA = collect ([ 1 , 2 , 3 ]);
$ collectionB = $ collectionA -> collect ();
$ collectionB -> all ();
// [1, 2, 3]
combine
This method applies to more than one array, assuming we have an array with name and age values and another with a causal value of 20. Now if we combine these two arrays, the final array becomes [’20 ‘<=’ age ‘,’ Ali ‘<=’ name ‘].
$ collection = collect ([ 'name' , 'age' ]);
$ combined = $ collection -> combine ([ 'George' , 29 ]);
$ combined -> all ();
// ['name' => 'George', 'age' => 29]
contact
This method puts the values of two or more arrays in one array.
$ collection = collect ([ 'John Doe' ]);
$ concatenated = $ collection -> concat ([ 'Jane Doe' ]) -> concat ([ 'name' => 'Johnny Doe' ]);
$ concatenated -> all ();
// ['John Doe', 'Jane Doe', 'Johnny Doe']
contains
We use this method when we want to know if there is a value in an array.
$ collection = collect ([ 'name' => 'Desk' , 'price' => 100 ]);
$ collection -> contains ( 'Desk' );
// true
$ collection -> contains ( 'New York' );
// false
We can also check if a Key and Value exists in an array simultaneously.
$ collection = collect ([
[ 'product' => 'Desk' , 'price' => 200 ],
[ 'product' => 'Chair' , 'price' => 100 ],
]);
$ collection -> contains ( 'product' , 'Bookcase' );
// false
count
This method returns the amount of data in a collection or array.
$ collection = collect ([ 1 , 2 , 3 , 4 ]);
$ collection -> count ();
// 4
country
This method returns the number of iterations of each data.
$ collection = collect ([ 1 , 2 , 2 , 2 , 3 ]);
$ counted = $ collection -> countBy ();
$ counted -> all ();
// [1 => 1, 2 => 3, 3 => 1]
cross join
This method, for example, when applied to two arrays, assigns the first data of the first array to all the data of the second array, the second data of the first array to all the data of the second array, and so on.
$ collection = collect ([ 1 , 2 ]);
$ matrix = $ collection -> crossJoin ([ 'a' , 'b' ]);
$ matrix -> all ();
/ *
[
[1, 'a'],
[1, 'b'],
[2, 'a'],
[2, 'b'],
]
* /
$ collection = collect ([ 1 , 2 ]);
$ matrix = $ collection -> crossJoin ([ 'a' , 'b' ], [ 'I' , 'II' ]);
$ matrix -> all ();
/ *
[
[1, 'a', 'I'],
[1, 'a', 'II'],
[1, 'b', 'I'],
[1, 'b', 'II'],
[2, 'a', 'I'],
[2, 'a', 'II'],
[2, 'b', 'I'],
[2, 'b', 'II'],
]
* /
dd
This method displays all the requested data wherever it comes from the code, after which the continuation of the code will stop.
$ collection = collect ([ 'John Doe' , 'Jane Doe' ]);
$ collection -> dd ();
/ *
Collection {
#items: array: 2 [
0 => "John Doe"
1 => "Jane Doe"
]
}
* /
If you do not want the code to continue, you can use dump instead of dd.
dump
This method displays all the requested data wherever it comes from the code and continues after it.
The dump method dumps the collection 's items:
$ collection = collect ([' John Doe ', ' Jane Doe ']);
$ collection-> dump ();
/ *
Collection {
#items: array: 2 [
0 => "John Doe"
1 => "Jane Doe"
]
}
* /
diff
If applied to two arrays, this method returns all the data that exists in the first array but does not exist in the second array.
$ collection = collect ([ 1 , 2 , 3 , 4 , 5 ]);
$ diff = $ collection -> diff ([ 2 , 4 , 6 , 8 ]);
$ diff -> all ();
// [1, 3, 5]
diffAssoc
This method works the same as the diff method, except that instead of checking the Values, both the Value and the Key match two or more arrays, and if the same Key and Value as in the first array do not exist in the second array. If the Key and Value return the first array.
$ collection = collect ([
'color' => 'orange' ,
'type' => 'fruit' ,
'remain' => 6 ,
]);
$ diff = $ collection -> diffAssoc ([
'color' => 'yellow' ,
'type' => 'fruit' ,
'remain' => 3 ,
'used' => 6 ,
]);
$ diff -> all ();
// ['color' => 'orange', 'remain' => 6]
differs
This method works the same as the diff method, except it examines the keys instead of the values.
$ collection = collect ([
'one' => 10 ,
'two' => 20 ,
'three' => 30 ,
'four' => 40 ,
'five' => 50 ,
]);
$ diff = $ collection -> diffKeys ([
'two' => 2 ,
'four' => 4 ,
'six' => 6 ,
'eight' => 8 ,
]);
$ diff -> all ();
// ['one' => 10, 'three' => 30, 'five' => 50]
duplicates
This method returns all data that has been repeated twice.
$ collection = collect ([ 'a' , 'b' , 'a' , 'c' , 'b' ]);
$ collection -> duplicates ();
// [2 => 'a', 4 => 'b']
If we want to look for values that have been repeated twice in one or more arrays between specific keys, we do the following.
$ employees = collect ([
[ 'email' => 'abigail@example.com' , 'position' => 'Developer' ],
[ 'email' => 'james@example.com' , 'position' => 'Designer' ],
[ 'email' => 'victoria@example.com' , 'position' => 'Developer' ],
])
$ employees -> duplicates ( 'position' );
// [2 => 'Developer']
each
This method separates and returns all the data in an array-like a for each loop.
$ collection -> each ( function ( $ item , $ key ) {
//
});
except
This method returns all the data in an array except the entered values.
$ collection = collect ([ 'product_id' => 1 , 'price' => 100 , 'discount' => false ]);
$ filtered = $ collection -> except ([ 'price' , 'discount' ]);
$ filtered -> all ();
// ['product_id' => 1]
first
This method returns the first data of an array.
collect ([ 1 , 2 , 3 , 4 ]) -> first ();
// 1
firstWhere
This method returns the first data of an array with the specific condition we express.
$ collection = collect ([
[ 'name' => 'Regena' , 'age' => null ],
[ 'name' => 'Linda' , 'age' => 14 ],
[ 'name' => 'Diego' , 'age' => 23 ],
[ 'name' => 'Linda' , 'age' => 84 ],
]);
$ collection -> firstWhere ( 'name' , 'Linda' );
// ['name' => 'Linda', 'age' => 14]
For example, in the code above, we get the first data called Linda.
$ collection -> firstWhere ( 'age' , '> =' , 18 );
// ['name' => 'Diego', 'age' => 23]
Or in this example, we get the first data that is older than 18.
flip
This method replaces the Key and Value of the array.
$ collection = collect ([ 'name' => 'taylor' , 'framework' => 'laravel' ]);
$ flipped = $ collection -> flip ();
$ flipped -> all ();
// ['taylor' => 'name', 'laravel' => 'framework']
forget
This method clears a Key and Value from the array.
$ collection = collect ([ 'name' => 'taylor' , 'framework' => 'laravel' ]);
$ collection -> forget ( 'name' );
$ collection -> all ();
// ['framework' => 'laravel']
get
In this method, by calling the key of a data, you can read the value of that data.
$ collection = collect ([ 'name' => 'taylor' , 'framework' => 'laravel' ]);
$ value = $ collection -> get ( 'name' );
// taylor
groupBy
This method groups an array. When we pass a value to this method, different groups of data in that array are created according to that value.
$ collection = collect ([
[ 'account_id' => 'account-x10' , 'product' => 'Chair' ],
[ 'account_id' => 'account-x10' , 'product' => 'Bookcase' ],
[ 'account_id' => 'account-x11' , 'product' => 'Desk' ],
]);
$ grouped = $ collection -> groupBy ( 'account_id' );
$ grouped -> toArray ();
/ *
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
* /
has
This method checks the presence of one or more data in an array.
$ collection = collect ([ 'account_id' => 1 , 'product' => 'Desk' , 'amount' => 5 ]);
$ collection -> has ( 'product' );
// true
$ collection -> has ([ 'product' , 'amount' ]);
// true
$ collection -> has ([ 'amount' , 'price' ]);
// false
implode
This method merges the values of an array.
$ collection = collect ([
[ 'account_id' => 1 , 'product' => 'Desk' ],
[ 'account_id' => 2 , 'product' => 'Chair' ],
]);
$ collection -> implode ( 'product' , ',' );
// Desk, Chair
collect ([ 1 , 2 , 3 , 4 , 5 ]) -> implode ( '-' );
// '1-2-3-4-5'
intersect
This method shows us all the data in the first and second arrays when comparing the two arrays.
$ collection = collect ([ 'Desk' , 'Sofa' , 'Chair' ]);
$ intersect = $ collection -> intersect ([ 'Desk' , 'Chair' , 'Bookcase' ]);
$ intersect -> all ();
// [0 => 'Desk', 2 => 'Chair']
The new data key is the same as the first array key
intersectByKeys
This method shows all the keys in the first and second arrays and the Value of the first array when comparing the two arrays.
$ collection = collect ([
'serial' => 'UX301' , 'type' => 'screen' , 'year' => 2009 ,
]);
$ intersect = $ collection -> intersectByKeys ([
'reference' => 'UX404' , 'type' => 'tab' , 'year' => 2011 ,
]);
$ intersect -> all ();
// ['type' => 'screen', 'year' => 2009]
isEmpty
This method checks that an array is empty.
collect ([]) -> isEmpty ();
// true
is not empty
This method checks that an array is not empty.
collect ([]) -> isNotEmpty ();
// false
join
This method merges the values of an array as we wish.
collect ([ 'a' , 'b' , 'c' ]) -> join ( ',' ); // 'a, b, c'
collect ([ 'a' , 'b' , 'c' ]) -> join ( ',' , ', and' ); // 'a, b, and c'
collect ([ 'a' , 'b' ]) -> join ( ',' , 'and' ); // 'a and b'
collect ([ 'a' ]) -> join ( ',' , 'and' ); // 'a'
collect ([]) -> join ( ',' , 'and' ); // ''
last
This method returns the last data of an array.
collect ([ 1 , 2 , 3 , 4 ]) -> last ( function ( $ value , $ key ) {
return $ value < 3 ;
});
// 2
collect ([ 1 , 2 , 3 , 4 ]) -> last ();
// 4
max
This method returns the largest data in an array.
$ max = collect ([[ 'foo' => 10 ], [ 'foo' => 20 ]]) -> max ( 'foo' );
// 20
$ max = collect ([ 1 , 2 , 3 , 4 , 5 ]) -> max ();
// 5
median
This method returns the middle data of an array and returns its average if two arrays are in the middle.
$ median = collect ([[ 'foo' => 10 ], [ 'foo' => 10 ], [ 'foo' => 20 ], [ 'foo' => 40 ]]) -> median ( 'foo' );
// 15
$ median = collect ([ 1 , 1 , 2 , 4 ]) -> median ();
// 1.5
merge
This method binds the data of an array together and puts it in the final array if one of the data is in the second array.
$ collection = collect ([ 'product_id' => 1 , 'price' => 100 ]);
$ merged = $ collection -> merge ([ 'price' => 200 , 'discount' => false ]);
$ merged -> all ();
// ['product_id' => 1, 'price' => 200, 'discount' => false]
$ collection = collect ([ 'Desk' , 'Chair' ]);
$ merged = $ collection -> merge ([ 'Bookcase' , 'Door' ]);
$ merged -> all ();
// ['Desk', 'Chair', 'Bookcase', 'Door']
merge-recursive
This method binds the data of an array together, and if data is repeated, it puts both of them in the final array.
$ collection = collect ([ 'product_id' => 1 , 'price' => 100 ]);
$ merged = $ collection -> mergeRecursive ([ 'product_id' => 2 , 'price' => 200 , 'discount' => false ]);
$ merged -> all ();
// ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false]
min
This method returns the smallest data in an array.
$ min = collect ([[ 'foo' => 10 ], [ 'foo' => 20 ]]) -> min ( 'foo' );
// 10
$ min = collect ([ 1 , 2 , 3 , 4 , 5 ]) -> min ();
// 1
pluck
This method returns all the values of an array with a specific key.
$ collection = collect ([
[ 'product_id' => 'prod-100' , 'name' => 'Desk' ],
[ 'product_id' => 'prod-200' , 'name' => 'Chair' ],
]);
$ plucked = $ collection -> pluck ( 'name' );
$ plucked -> all ();
// ['Desk', 'Chair']
pop
This method first shows us the last data of an array and then removes it from the main array.
$ collection = collect ([ 1 , 2 , 3 , 4 , 5 ]);
$ collection -> pop ();
// 5
$ collection -> all ();
// [1, 2, 3, 4]
prepend
This method adds data to the beginning of an array.
$ collection = collect ([ 1 , 2 , 3 , 4 , 5 ]);
$ collection -> prepend ( 0 );
$ collection -> all ();
// [0, 1, 2, 3, 4, 5]
pull
This Value method first shows us a key and then removes it from the main array.
$ collection = collect ([ 'product_id' => 'prod-100' , 'name' => 'Desk' ]);
$ collection -> pull ( 'name' );
// 'Desk'
$ collection -> all ();
// ['product_id' => 'prod-100']
push
This method adds data to the end of an array.
$ collection = collect ([ 1 , 2 , 3 , 4 ]);
$ collection -> push ( 5 );
$ collection -> all ();
// [1, 2, 3, 4, 5]
put
This method adds a Key and Value to the end of an array.
$ collection = collect ([ 'product_id' => 1 , 'name' => 'Desk' ]);
$ collection -> put ( 'price' , 100 );
$ collection -> all ();
// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]
random
This method returns data at random.
$ collection = collect ([ 1 , 2 , 3 , 4 , 5 ]);
$ collection -> random ();
// 4 - (retrieved randomly)
replace
This method generates dual array data if it is displaced and if it is not.
$ collection = collect ([ 'Taylor' , 'Abigail' , 'James' ]);
$ replaced = $ collection -> replace ([ 1 => 'Victoria' , 3 => 'Finn' ]);
$ replaced -> all ();
// ['Taylor', 'Victoria', 'James', 'Finn']
reverse
This method organizes the data of an array from end to beginning.
$ collection = collect ([ 'a' , 'b' , 'c' , 'd' , 'e' ]);
$ reversed = $ collection -> reverse ();
$ reversed -> all ();
/ *
[
4 => 'e',
3 => 'd',
2 => 'c',
1 => 'b',
0 => 'a',
]
* /
search
This Key method finds a Value.
$ collection = collect ([ 2 , 4 , 6 , 8 ]);
$ collection -> search ( 4 );
// 1
shift
This method first shows us the data of an array and then removes it from the original array.
$ collection = collect ([ 1 , 2 , 3 , 4 , 5 ]);
$ collection -> shift ();
// 1
$ collection -> all ();
// [2, 3, 4, 5]
shuffle
This method breaks down the data of an array.
$ collection = collect ([ 1 , 2 , 3 , 4 , 5 ]);
$ shuffled = $ collection -> shuffle ();
$ shuffled -> all ();
// [3, 2, 5, 1, 4] - (generated randomly)
sort
This method sorts the data of an array from small to large.
$ collection = collect ([ 5 , 3 , 1 , 2 , 4 ]);
$ sorted = $ collection -> sort ();
$ sorted -> values () -> all ();
// [1, 2, 3, 4, 5]
sortBy
This method sorts the data of an array from small to large according to the key entered.
$ collection = collect ([
[ 'name' => 'Desk' , 'price' => 200 ],
[ 'name' => 'Chair' , 'price' => 100 ],
[ 'name' => 'Bookcase' , 'price' => 150 ],
]);
$ sorted = $ collection -> sortBy ( 'price' );
$ sorted -> values () -> all ();
/ *
[
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
['name' => 'Desk', 'price' => 200],
]
* /
sortDesc
This method sorts the data of an array from large to small.
$ collection = collect ([ 5 , 3 , 1 , 2 , 4 ]);
$ sorted = $ collection -> sortDesc ();
$ sorted -> values () -> all ();
// [5, 4, 3, 2, 1]
sortKeys
This method sorts the keys of an array from uppercase to lowercase.
$ collection = collect ([
'id' => 22345 ,
'first' => 'John' ,
'last' => 'Doe' ,
]);
$ sorted = $ collection -> sortKeys ();
$ sorted -> all ();
/ *
[
'first' => 'John',
'id' => 22345,
'last' => 'Doe',
]
* /
splice
This method deletes an arbitrary amount of data in an array and then restores it.
$ collection = collect ([ 1 , 2 , 3 , 4 , 5 ]);
$ chunk = $ collection -> splice ( 2 );
$ chunk -> all ();
// [3, 4, 5]
$ collection -> all ();
// [1, 2]
sum
This method returns the data of an array.
collect ([ 1 , 2 , 3 , 4 , 5 ]) -> sum ();
// 15
$ collection = collect ([
[ 'name' => 'JavaScript: The Good Parts' , 'pages' => 176 ],
[ 'name' => 'JavaScript: The Definitive Guide' , 'pages' => 1096 ],
]);
$ collection -> sum ( 'pages' );
// 1272
toArray
This method converts a Collection into an array.
$ collection = collect ([ 'name' => 'Desk' , 'price' => 200 ]);
$ collection -> toArray ();
/ *
[
['name' => 'Desk', 'price' => 200],
]
* /
toJson
This method converts a Collection to Json format code.
$ collection = collect ([ 'name' => 'Desk' , 'price' => 200 ]);
$ collection -> toJson ();
// '{"name": "Desk", "price": 200}'
unique
This method returns data that has only been repeated once.
$ collection = collect ([ 1 , 1 , 2 , 2 , 3 , 4 , 2 ]);
$ unique = $ collection -> unique ();
$ unique -> values () -> all ();
// [1, 2, 3, 4]
$ collection = collect ([
[ 'name' => 'iPhone 6' , 'brand' => 'Apple' , 'type' => 'phone' ],
[ 'name' => 'iPhone 5' , 'brand' => 'Apple' , 'type' => 'phone' ],
[ 'name' => 'Apple Watch' , 'brand' => 'Apple' , 'type' => 'watch' ],
[ 'name' => 'Galaxy S6' , 'brand' => 'Samsung' , 'type' => 'phone' ],
[ 'name' => 'Galaxy Gear' , 'brand' => 'Samsung' , 'type' => 'watch' ],
]);
$ unique = $ collection -> unique ( 'brand' );
$ unique -> values () -> all ();
/ *
[
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
]
* /
$ unique = $ collection -> unique ( function ( $ item ) {
return $ item [ 'brand' ]. $ item [ 'type' ];
});
$ unique -> values () -> all ();
/ *
[
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]
* /
where
This method returns data with the conditions we enter.
$ collection = collect ([
[ 'product' => 'Desk' , 'price' => 200 ],
[ 'product' => 'Chair' , 'price' => 100 ],
[ 'product' => 'Bookcase' , 'price' => 150 ],
[ 'product' => 'Door' , 'price' => 100 ],
]);
$ filtered = $ collection -> where ( 'price' , 100 );
$ filtered -> all ();
/ *
[
['product' => 'Chair', 'price' => 100],
['product' => 'Door', 'price' => 100],
]
* /
$ collection = collect ([
[ 'name' => 'Jim' , 'deleted_at' => '2019-01-01 00:00:00' ],
[ 'name' => 'Sally' , 'deleted_at' => '2019-01-02 00:00:00' ],
[ 'name' => 'Sue' , 'deleted_at' => null ],
]);
$ filtered = $ collection -> where ( 'deleted_at' , '! =' , null );
$ filtered -> all ();
/ *
[
['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'],
['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'],
]
* /
whereBetween
This method returns data that is between two specific values.
$ collection = collect ([
[ 'product' => 'Desk' , 'price' => 200 ],
[ 'product' => 'Chair' , 'price' => 80 ],
[ 'product' => 'Bookcase' , 'price' => 150 ],
[ 'product' => 'Pencil' , 'price' => 30 ],
[ 'product' => 'Door' , 'price' => 100 ],
]);
$ filtered = $ collection -> whereBetween ( 'price' , [ 100 , 200 ]);
$ filtered -> all ();
/ *
[
['product' => 'Desk', 'price' => 200],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]
* /
Conclusion :
In this article, we briefly and practically review the collections available in Laravel, and we became very familiar with this extraordinary feature of Laravel.