Web Development 2 min read 392 words

Laravel Collections: Arrays on steroids

ES
Laravel Collections: Arrays on steroids

Laravel, in addition to using multiple third-party packages, is also possible to use parts as components. All components are under the “Illuminate” namespace.

If there’s a really interesting and useful class, it’s Collection, which allows us to work with data arrays in a simple and “programmatic” way.

To have this class in our project, we only need the illuminate/support package which we can install with:

composer require illuminate/support:5.2.x-dev

To show some examples, we’ll use a small array with this data:

$array = [
    [
        'id' => 12,
        'name' => 'El rinconcillo',
        'category' => 'Bar',
        'visits' => 102,
        'stars' => 4.2,
        'average_price' => 20,
        'city' => 'Sevilla',
        'region' => 'Andalucía',
    ],
    [
        'id' => 30,
        'name' => 'El Choco',
        'category' => 'Bar',
        'visits' => 65,
        'stars' => 4.9,
        'average_price' => 12,
        'city' => 'Pontecesures',
        'region' => 'Galicia',
    ],
    [
        'id' => 89,
        'name' => 'La Azotea',
        'category' => 'Restaurant',
        'visits' => 165,
        'stars' => 4.7,
        'average_price' => 30,
        'city' => 'Sevilla',
        'region' => 'Andalucía',
    ],
    [
        'id' => 22,
        'name' => 'Casa Paco',
        'category' => 'Restaurant',
        'visits' => 15,
        'stars' => 3.7,
        'average_price' => null,
        'city' => 'Sevilla',
        'region' => 'Andalucía',
    ]
];

With this, we’ll create our collection object like this:

$places = new  Illuminate\Support\Collection(  $array  ) ;

Now we’ll see some examples of what can be done

Get an array (key => value) with the elements:

$list = $places->pluck( 'name', 'id')->all() ;

Result:

Array
(
    [12] => El rinconcillo
    [30] => El Choco
    [89] => La Azotea
    [22] => Casa Paco
)

Get the restaurant with the highest rating

$best_restaurant = $places
    ->where('category', 'Restaurant')
    ->sortByDesc( 'stars')
    ->take( 1 )
    ->toArray(   );
;

Get the sum of visits by business type

$visits_by_category  =  $places
        ->groupBy( 'category')
        ->map( function( $value, $key ) {
        return $value->reduce( function( $prev, $next){
            return $prev + $next['visits'];
        }, 0 );
     })
    ->toArray();

The average of prices, by region, if the price is null we won’t take it into consideration:

$average_prices_by_region = $places->groupBy('region')
    ->map(function ($value, $key) {
        return $value->reject(function ($value, $key) {
            return is_null($value['average_price']);
        })
            ->reduce(function ($prev, $next) {
                if ( empty( $prev)) {
                    $prev = $next['average_price'];
                }
                return ( $prev + $next['average_price'] ) / 2  ;
            } );

    })->toArray();

These are just a few examples that show a small part of the possibilities of this powerful class, and like everything in Laravel, it has complete documentation at: https://laravel.com/docs/5.2/collections