Hardist
Hardist

Reputation: 1993

Laravel Custom Collections

I'm trying to understand something. Consider the following:

$collection = collect(['example1' => 'test1', 'example2' => 'test2']);

When I do the following, I end up with this result:

Collection {#867 ▼
  #items: array:2 [▼
    "example1" => test1
    "example2" => test2
  ]
}

What I want to be able to do is this:

echo $collection->example1 // Should display test1

But instead it says "Trying to get property of non object".

So, I have two questions:

  1. Can somebody explain the above behaviour?
  2. Can somebody help with a solution so I can do $collection->example1?

Upvotes: 1

Views: 618

Answers (1)

OneLiner
OneLiner

Reputation: 611

Collections are objects containing an array. If you look back at what you posted you can see that you have an object of class Collection that contains an item which is an array. You can access the array items in normal array syntax or using the object's getter.

$product->get('subscription'); //object oriented way
$product['subscription']; //access as an array item

Upvotes: 2

Related Questions