Adding new property to Eloquent Collection

20,655

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.

Share:
20,655
Shafi
Author by

Shafi

Software engineer by profession and passion. Love to learn new things, ideas and help others to learn something.

Updated on November 19, 2020

Comments

  • Shafi
    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
    Shafi over 6 years
    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".
  • Marcin Nabiałek
    Marcin Nabiałek over 6 years
    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.
  • Shafi
    Shafi over 6 years
    Got the point I was missing. Accepting your answer. Thanks for your effort.