0

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?

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

And to answer "How can I wrap an object into a collection without turning it into an associative array?" you need to collect([ $obj ]).
That's possible but it still won't let them do $obj->count. Accessing it via array notation ($obj[0]->count) remains
It could very well be that I'm using the collection wrong. But, similar situation when using array of objects collect([$obj1, $obj2]). Would like collection helpers to chain e.g. filter / except / ... . E.g. for the collection return the objects, except its now property and then group them by count. This works fine for Laravel models but not for simple objects?
It's a bit vague to answer that. Isn't that a whole new question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.