Adding new property to Eloquent Collection
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.
Shafi
Software engineer by profession and passion. Love to learn new things, ideas and help others to learn something.
Updated on November 19, 2020Comments
-
Shafi over 3 years
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?
-
Shafi over 6 yearsThanks for your answer. Ok, laravel documentation tells, query like 'all' or 'get' returns instance of
Illuminate\Database\Eloquent\Collection
. So shouldn't besetAttribute
method available? And I updated the example of "using put method". -
Marcin Nabiałek over 6 yearsNo, setAttribute is available for single model, and you don't use here anywhere
get
orall
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. -
Shafi over 6 yearsGot the point I was missing. Accepting your answer. Thanks for your effort.