Marissa
Marissa

Reputation: 215

Laravel $collection->key = "value" doesn't work

The following code doesn't work in Laravel 7.

$collection = collect();
$collection->key = "value"
Log::debug($collection) // returns empty array []

But this code does.

$user = Auth::user();
$user->key = "value" 

If I understand correctly, Auth::user() should also return a collection. Why doesn't the first one work but the second one does?

Using a decoded JSON object also appears to work

$object = json_decode($data);
$object->key = "value"

It does work if you use $collection->put('key', 'value') but I'm curious as to why the first way doesn't seem to work.

Upvotes: 0

Views: 1019

Answers (2)

Watercayman
Watercayman

Reputation: 8168

You are trying to pull a single value from a collection in the first instance. You need to add an object to the collection and then attach a value to that object for it to work.

The second example:

$user = Auth::user();
$user->key = "value" 

works because $user is a single object. It is equivalent to what you might get from a first() or find($id) directive - single object that will take a value rather than a collection which will not.

You can create your own object and add the key you wish to it:

$object = new \stdClass();
$object->value = 'Your Value';

Now you can dump to Log with the string portion: Log::debug($object->value);

Or as you note, Log just needs a string, so JSON works too:

Log::debug(json_encode($object))

Upvotes: 2

Felippe Duarte
Felippe Duarte

Reputation: 15131

Use put() method instead:

$collection->put('key', 'value');

https://laravel.com/docs/7.x/collections#method-put

Auth::user() returns a type of Model class

Upvotes: 2

Related Questions