Manually add an item to an existing object [Laravel 5]

Here is what I am trying 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 it 'test' => truewill be added as a new key, but I want to insert it into Question, so I can access it like this with foreach$q -> test

So here is how I want to access the element:

@foreach($q as $qq)
{{ $qq->test }}
@endforeach
+4
source share
2 answers

, setAttribute() Eloquent (https://github.com/illuminate/database/blob/master/Eloquent/Model.php).
, setAttribute(), $SomeModel- > some_field, __ get() .

:

$Question = Question::find($id);
$Question->setAttribute('test', 'blablabla');
+8

setAttribute(), put() . map() , .

+2

Source: https://habr.com/ru/post/1598362/


All Articles