Manually add item to existing object [Laravel 5]
Asked Answered
L

3

19

Here is what I try to do:

$q = Question::where('id',$id -> id)->get();
$q[] = $q->push([ 'test' => true]); 
dd($q);

This will output:

Collection {#220 ▼
  #items: array:3 [▼
    0 => Question {#225 ▶}
    1 => array:1 [▼
      "test" => true
    ]
    2 => null
  ]
}

So 'test' => true will append as a new key, but I want to insert it in Question so latter I can access to it like this with foreach $q -> test

So here is how I want access to item:

@foreach($q as $qq)
{{ $qq->test }}
@endforeach
Leadsman answered 17/7, 2015 at 11:9 Comment(6)
I don't understan 1 thing: Question::where('id',$id -> id)->get(); why You do not get element by primary key just using: Question::find($id); ?Haymaker
So funny to get collection of rows when it's always unique (:Haymaker
If I use find is possible then to add new random attribut? to existing objectLeadsman
of course but, You'll lose ORM functions of it.Haymaker
Ok,how can I do that?Leadsman
read answer, updated itHaymaker
H
47

It can be done by using setAttribute() function of Eloquent Model (https://github.com/illuminate/database/blob/master/Eloquent/Model.php).
As You can see it stores data in protected $attributes using setAttribute(), and when we do $SomeModel->some_field it uses magic method __get() to retrieve item by association from attributes array.

Here is the resolution to Your question:

$Question = Question::find($id);
$Question->setAttribute('test', 'blablabla');
Haymaker answered 17/7, 2015 at 12:56 Comment(7)
It will just create new object, it will not add attribute to my existing object... I taking attrinuts from database: $q = Question::where('id',$id -> id)->get(); and I need on that attributes to add new one.Leadsman
I am not sure it syntax ok? I get: Cannot pass parameter 1 by referenceLeadsman
It's now better but don't add new item inside attributes it adding on the end of object. any way to fix it?Leadsman
here is picture: dodaj.rs/f/1o/ci/3p3OfzA3/screenshot-07172015-0345.pngLeadsman
Try secondary way, by using setAttribute method of EloquentHaymaker
Let us continue this discussion in chat.Haymaker
@Vladimir Djukic @Haymaker In subsequent loops, how would I push to the array that was set up in the initial loop with setAttribute()? I don't want to overwrite was was already set.Transmontane
S
6

Apart from setAttribute(), you can use put() refer to this post for one item. And map() for many items, refer to this post.

Succedaneum answered 14/6, 2017 at 2:23 Comment(0)
L
0

Simply add new attribute like this

$Q = Question::find($id);
$Q->new_attribute = 'data';

In foreach:

foreach($questions as $k=>$q){
   $q->new_attribute = 'data';
   $questions[$k] = $q;
}
Liles answered 30/4 at 6:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.