Laravel Collections Using Array Syntax

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

The Collection object implements the ArrayAccess and IteratorAggregate interface, allowing it to be used like an array.

Access collection element:

 $collection = collect([1, 2, 3]);
 $result = $collection[1];

Result: 2

Assign new element:

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

Result: $collection is [1, 2, 3, 4]

Loop collection:

$collection = collect(["a" => "one", "b" => "two"]);
$result = "";
foreach($collection as $key => $value){
    $result .= "(".$key.": ".$value.") ";        
}

Result: $result is (a: one) (b: two)

Array to Collection conversion:

To convert a collection to a native PHP array, use:

$array = $collection->all();
//or
$array = $collection->toArray()

To convert an array into a collection, use:

$collection = collect($array);

Using Collections with Array Functions

Please be aware that collections are normal objects which won't be converted properly when used by functions explicitly requiring arrays, like array_map($callback).

Be sure to convert the collection first, or, if available, use the method provided by the Collection class instead: $collection->map($callback)



Got any Laravel Question?