What is a Laravel collection?

It is basically a API wrapper for PHP array functions. But it has much more features which benefit array processing.

1. Avoid braces hell

think this case with at 5 braces:

 shuffle(shuffle(arsort(array_unique(array_merge($array1,$array2)))));

This is hell, if the array with more than 10 braces, you might lose track of the brace in the end. However, if you use Collection, it can be replaced with:

collect($array1)
     ->merge($array2)
     ->unique()
     ->sort()
     ->shuffle()
     ->shuffle()

This is more readable, object-oriented and flow-thinking.

2. Unify the use of API

It is PHP original API issue that you never know where the array should in parameter. they just not consistent. for example:

    array_walk ( $array , $callback );
    array_map ( $callback , $array);
    array_merge ( $array1 ,$array2 );// return a new array
    array_push ($array1 ,$value); // not return a new array

Laravel Collect just provide consistent API make my life easier.

    collect($array)
         ->each($callback)
         ->map($callback)
         ->merge($array2)
         ->push($value)

3.Collection API process key-value array better

Laravel focus on processing data from a database. So many cases are with key-value array situation, rather than an indexed array. So Laravel collection has many extended methods against the original PHP functions, which process with key of the array . For example:

 $array=[
        ["id"=>1,"name"=>"Apple"],
        ["id"=>2,"name"=>"Banana"],
        ["id"=>1,"name"=>"Apple"],
        ["id"=>2,"name"=>"Banana"],
    ];

    $result= collect($array)->unique("id");

The result will be:

 Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Apple
        )

    [1] => Array
        (
            [id] => 2
            [name] => Banana
        )

)

4. Dealing with multi layer array

Most of PHP original array API only deal with the top layer of an array. if you want to process the deep layer of an array, the code might become much more complex. But many APIs of Laravel collection allow you to access the deep layer of the array.

For example:

 $array=[
        ["id"=>1,"product"=>['name'=>"Apple"]],
        ["id"=>2,"product"=>['name'=>"Watermelon"]],
        ["id"=>3,"product"=>['name'=>"Banana"]],

    ];

    $result= collect($array)->sortBy("product.name");

The result will be:

Array
(
    [0] => Array
        (
            [id] => 1
            [product] => Array
                (
                    [name] => Apple
                )

        )

    [2] => Array
        (
            [id] => 3
            [product] => Array
                (
                    [name] => Banana
                )

        )

    [1] => Array
        (
            [id] => 2
            [product] => Array
                (
                    [name] => Watermelon
                )

        )

)

5. More missing array helpers from the original PHP

Besides above, Laravel collection increases many very useful array APIs in each new versions. Many useful Helpers were designed to process the Key-Value type of the array and so useful for developing the application. like: keyBy(), where(), isEmpty(), isNotEmpty() and so on.

Furthermore, Collection is macroable which means you can extend Collection API, make Collection much more suitable for your project.

All in all, The Laravel collection is powerful array processing Helper for my development.


Collection is convenient wrapper for working with arrays of data. Collections have all conveniences of arrays and also bunch of their own helpers.

The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data. As you can see, the Collection class allows you to chain its methods to perform fluent mapping and reducing of the underlying array. In general, collections are immutable, meaning every Collection method returns an entirely new Collection instance.

https://laravel.com/docs/5.3/collections


Think of a Collection as an array on steroids. It is an object that works the same as an array - that is, you can get items with $collection['item'] and set them with $collection['foo'] = 'bar' - but it comes with additional methods for higher-level functions that make common operations easier. These methods are often an alternative for using foreach and manually manipulating arrays. Adam Wathan has some good practical examples of the benefits you might get from using collections instead of arrays. There are also good introductions elsewhere online.

Tags:

Php

Laravel