Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a Laravel collection?

Tags:

php

laravel

What is a Laravel collection? what is a difference between a PHP array and a Laravel collection?

It seems collections are very similar to arrays. For example, result retrieved via the get() method is a collection of data. But when we want to use it as an array we must use toArray() method. Why?

like image 416
Iman Sedighi Avatar asked Jan 04 '17 14:01

Iman Sedighi


People also ask

What is a Collection in PHP?

Collection is the base interface which covers functionality common to all the data structures in this library. It guarantees that all structures are traversable, countable, and can be converted to json using json_encode().

What is the difference between array and Collection in Laravel?

An Array is a basic data structure that stores one or many items in a single variable. PHP arrays have a massive problem with not being OOP. Illuminate\Support (Laravel) Collection comes with help. Laravel Collection is a fluent OOP wrapper for working with arrays.

Is a Collection an object in Laravel?

Collections are basically an extension to the php native array. It's meant to work with arrays. The arrays can certainly contain objects, such as eloquent results, but at the core it's an array.

What is eloquent Collection?

Eloquent collections are an extension of Laravel's Collection class with some handy methods for dealing with query results. The Collection class itself, is merely a wrapper for an array of objects, but has a bunch of other interesting methods to help you pluck items out of the array.


2 Answers

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.

like image 189
caoglish Avatar answered Oct 05 '22 23:10

caoglish


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

like image 42
Alexey Mezenin Avatar answered Oct 06 '22 00:10

Alexey Mezenin