Adding new property to Eloquent Collection
Asked Answered
P

1

8

Trying to add new property to existing collection and access that.

What I need is something like:

$text = Text::find(1);  //Text model has properties- id,title,body,timestamps
$text->user = $user;

And access the user via, $text->user.

Exploring on documentation and SO, I found put, prepend, setAttribute methods to do that.

$collection = collect();
$collection->put('a',1);
$collection->put('c',2);
echo $collection->c; //Error: Undefined property: Illuminate\Support\Collection::$c

Again,

$collection = collect();
$collection->prepend(1,'t');
echo $collection->t = 5; //Error: Undefined property: Illuminate\Support\Collection::$t

And

$collection = collect();
$collection->setAttribute('c',99); // Error: undefined method setAttribute
echo $collection->c;

Any help?

Patina answered 18/11, 2017 at 9:18 Comment(0)
P
8

I think you mix here Eloquent collection with Support collection. Also notice when you are using:

$text = Text::find(1);  //Text model has properties- id,title,body,timestamps
$text->user = $user;

you don't have here any collection but only single object.

But let's look at:

$collection = collect();
$collection->put('a',1);
echo $collection->c; //Error: Undefined property: Illuminate\Support\Collection::$c

You are taking c and you don't have such element. What you should do is taking element that is at a key like this:

echo $collection->get('a');

or alternatively using array access like this:

echo $collection['a'];

Also notice there is no setAttribute method on Collection. There is setAttribute method on Eloquent model.

Progesterone answered 18/11, 2017 at 18:58 Comment(4)
Thanks for your answer. Ok, laravel documentation tells, query like 'all' or 'get' returns instance of Illuminate\Database\Eloquent\Collection. So shouldn't be setAttribute method available? And I updated the example of "using put method".Patina
No, setAttribute is available for single model, and you don't use here anywhere get or all to get models. If you want to have collection of models you could use: $text = Text::where('id', 1)->get(); and now you have first model in $text[0] but obviously when you are looking by id it does not make any sense to have collection of results because you have only single element with this id.Numbskull
Got the point I was missing. Accepting your answer. Thanks for your effort.Patina
ok. When you use Laravel validation, the result of $validated = $validator->safe() is a collection, on which we can then use collection methods such as only(). And you can access the properties like an object: $validated->some_property How do I create such a collection, given an associative array to start?Menell

© 2022 - 2024 — McMap. All rights reserved.