A Collection does not expose the items keys as its Object properties; it implements ArrayAccess for this reason
Mar 11, 2020
10
Level 13
Collection Basics - How do I access elements of collection with `->` ?
I've been using eloquent collections for long time now; but this is first time I ever had to create my own custom collection from scratch.
$collection = collect(['one' => 1, 'two' => 2, 'three' => 3]);
Now I want to be able to say $collection->one and it should throw 1, but it doesn't. Instead, I've to write $collection['one'] to get the desired value.
What am I doing wrong?
Level 75
If you have:
$employees = collect([
['id' => 4, 'email' => null, 'position' => 'Developer'],
['id' => 7, 'email' => '[email protected]', 'position' => 'Designer'],
['id' => 9, 'email' => '[email protected]', 'position' => 'Developer'],
['id' => 2, 'email' => '[email protected]', 'position' => 'boss'],
]);
Works:
echo $employees[0]["id"];
Don't work
echo $employees[0]->id;
If you need objects
$newemployees = $employees->toJson();
$newemp = json_decode($newemployees);
then
echo $newemp[0]->id; //// 4
Gives:
Array
(
[0] => stdClass Object
(
[id] => 4
[email] =>
[position] => Developer
)
[1] => stdClass Object
(
[id] => 7
[email] => [email protected]
[position] => Designer
)
[2] => stdClass Object
(
[id] => 9
[email] => [email protected]
[position] => Developer
)
[3] => stdClass Object
(
[id] => 2
[email] => [email protected]
[position] => boss
)
)
@thebigk the trick here is to play around and experiment with this stuff in order to learn it.
1 like
Please or to participate in this conversation.