Search code examples
laravellaravel-collection

Laravel collection with ampersand undefined property


I am dding a collection like so as I'm having a problem looking for a property on the object:

dd($this->plan);

Output:

Illuminate\Support\Collection {#5314
  #items: array:3 [
    "ageRange" => "Under 18"
    "goal" => null
    "duration" => & "Indefinitely"
  ]
}

I am looking for the property duration on this object, but when I hit: $plan->duration I get the following error:

dd($this->plan->duration);

I get the following error:

Property [duration] does not exist on this collection instance.

I believe it's something to do with this & but I am not sure why it's there or where it's come from


Solution

  • That is an array, not an object inside the Collection. Try either $this->plan->get('duration') or $this->plan['duration']


    As the question/answer in the comment by @Peppermintology points out, this is a because the 'duration' key was set by reference. To illustrate, here's a quick way to reproduce the behavior in the tinker console:

    enter image description here