Manually add item to existing object [Laravel 5]

后端 未结 2 391
时光说笑
时光说笑 2021-01-04 07:27

Here is what I try to do:

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

This wi

相关标签:
2条回答
  • 2021-01-04 07:59

    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');
    
    0 讨论(0)
  • 2021-01-04 08:04

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

    0 讨论(0)
提交回复
热议问题