Shafi
Shafi

Reputation: 1970

Adding new property to Eloquent Collection

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?

Upvotes: 8

Views: 32683

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

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.

Upvotes: 8

Related Questions