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?
Illuminate\Database\Eloquent\Collection
. So shouldn't besetAttribute
method available? And I updated the example of "using put method". – Patina