wivku
wivku

Reputation: 2643

Laravel collection of object results in associative array instead of object?

When I wrap a regular object into a collection, the result is an associative array.

I would like to keep using it as an object.

$obj = (object) ['count'=>1, 'now'=>Carbon::now()];
dump($obj); // $obj->count = 1, $obj->now = Carbon {...}

$collection = collect($obj);
dump($collection); // unwanted: $collection['count'] = 1, $collection['now'] = Carbon {...}

In a similar question the offered solution is to json_encode/json_decode the $collection.
But that modifies the object and loses information (e.g. converts the now Carbon object to a string).

$collection = json_decode(collect($obj)->toJson());
dump($collection); // unwanted: $collection->count = 1, $collection->now = "2021-05-25T10:43:34.301505Z"

How can I wrap an object into a collection without turning it into an associative array?

Upvotes: 0

Views: 984

Answers (1)

shaedrich
shaedrich

Reputation: 5715

Maybe that's because a collection is considered an array of multiple entries. Technically, you're passing just one unwrapped entry whose properties are considered array entries for the collection. So I'd say, you're using the collection wrong.

From the docs:

The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data.

Another way of emphasizing this, is that the Collection class implements the ArrayAccess interface. Therefore, this is what happens: When creating a Collection via collect(), the passed data is set to $this->items. So Collection is not an array, it just lets you access the contents of $this->items via array notation.

Upvotes: 2

Related Questions