In Laravel collection can be a very handy tool. This is mainly due to the vast arsenal that come with it!

Laravel collection methods

Laravel Collections are like arrays in the most basic sense. The store a collection of items. These items can be objects, arrays, strings, numbers etc.

Create a collection

$myCollection = collect([1, 2, 3, 4, 5]);

You can use the collect() helper to quickly create a collection. Or basically any model or eloquent query returns a collection.

Collection Filter

To filter items in a collection is simple. Just use the filter() method on the collection and pass the callback with whichever conditions you want to filter.

$activeUsers = User::all()->filter(fn(User $user)=>$user->active == 1);

Or to filter even numbers from odd ones

$oddNumbers = collect([1,2,3,4,5,6,7])->filter(fn($number)=>$number%2!=0);

Collection using each method

The each() method allows us to perform a certain function on each item of the collection. This is mostly used when affecting external data. Though this is a terrible example, it shows the basic use of the each method.

$numberOfCows = 0;
$animals = collect(["dogs", "cows", "cats", "cows"])
			->each(function($animal) use(&$numberOfCows){
            	if($animal == "cows"){
                	$numberOfCows++;
                }
			});
 return $numberOfCows;
 2

Add item to collection

In Laravel To add another item to a created collection, you can use the method put(). Which takes the first argument as the key and the second argument as the value.

$numbers = collect(["one"=>1, "two"=>2,"three"=>3]);

$numbers->put("four",4);

$numbers->all();

["one"=>1, "two"=>2,"three"=>3, "four"=> 4]

Collection group by

If you may wish to group your items by certain key then you can use the groupBy() method. Which will provide chunks of similar data! And the grouping column becomes the key.

$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->all();

output
[
	'account-x10' => [
    	['account_id' => 'account-x10', 'product' => 'Chair'],
        ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    ],
    'account-x11' => [
    	['account_id' => 'account-x11', 'product' => 'Desk'],
    ],
]
An example from Laravel website

Checkout other Laravel methods

You can check the whole cocktail of Laravel methods in the Laravel documentation!