1

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

Lewis Smith
  • 1,271
  • 1
  • 14
  • 39
  • First just returns the first value in the array, so that's not helpful unfortunately – Lewis Smith May 19 '21 at 16:38
  • SO I've updated to provide a better example of the array, if I hit `$this->plan->first()` I get the string `Under 18` out and nothing else – Lewis Smith May 19 '21 at 16:44
  • (Cleaned up some comments). It's definitely clearer now; can you provide the code that generates this Collection? And does the answer below work? – Tim Lewis May 19 '21 at 16:47
  • The collection is provided by the front end as part of the request, all I do is collect it like so: `$this->plan = collect($plan);` – Lewis Smith May 19 '21 at 16:49
  • 1
    Gotcha! Apologies for the confusion. So you're basically doing `collect(['ageRange' => 'Under 18', 'goal' => null, 'duration' => 'Indefinitely'])`, which results in a Collection of that single array. And array access `['duration']` instead of object access `->duration` is the way to go. If you want `$this->plan->duration` to work, simply do `$this->plan = (object)$plan`. Still not sure about the `&` though – Tim Lewis May 19 '21 at 16:51

1 Answers1

3

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

IGP
  • 14,160
  • 4
  • 26
  • 43