Real Dreams
Real Dreams

Reputation: 18010

Setting nested array in Laravel collection class

Consider the following Laravel snippet:

$var = collect(['foo' => []]);
$var['foo']['x'] = 2;

It cause Notice: Indirect modification of overloaded element of Illuminate\Support\Collection has no effect in C:/…/file.php notice. What is it all about?

Upvotes: 4

Views: 2197

Answers (1)

samrap
samrap

Reputation: 5673

I know I have come across this problem before and I can tell you it is not Laravel related. This problem applies to any class that implements PHP's ArrayAccess interface. Let me explain.

If you take a look at PHP's ArrayAccess interface, you will see the following method:

abstract public mixed offsetGet ( mixed $offset )

Which, a common definition for this method would be something like:

public function offsetGet($offset) {
    return isset($this->container[$offset]) ? $this->container[$offset] : null;
}

Laravel's Collection object implements this ArrayAccess interface and it allows you to access objects as arrays.

So, what happens when you use the [] operator on this object? The offsetGet method is called and it returns an array, but not a reference to that array. So any changes you make will be made into space, since the returned array does not reference the actual array in the object. You can understand this more by looking into the ArrayAccess interface yourself, but what really matters is the solution.

$var = collect(['foo' => []]);

$temp = $var['foo'];
$temp['x'] = 2;

$var['foo'] = $temp;

Upvotes: 4

Related Questions