如何在集合 laravel 中添加新值?

How to add new value in collection laravel?

我在以下循环中尝试添加新值:

 foreach ($pro->sig()->get() as $key => $sig) {
            $sig->val = 2;
        }

当我打印 $pro->sig() 的输出时,我没有新值 $sig->val

在我的例子中,我试过如下

foreach ($user->emails as $key => $email) {
   $email->test = "test";
}
return $user->emails;

它输出像,

  {
    "id": 76,
    "user_id": 5,
    "additional_email": "test@test.com",
    "test": "test"
  }

请这样尝试。

如果您有一个集合,您可以使用 pushput 方法。

放置示例:

$collection = collect(['product_id' => 1, 'name' => 'Desk']);

$collection->put('test', 'test');

$collection->all();

输出将是:

['product_id' => 1, 'name' => 'Desk', 'test' => 'test']

推送示例:

$collection = collect([1, 2, 3, 4]);

$collection->push(5);

$collection->all();

输出:

[1, 2, 3, 4, 5]

参考:https://laravel.com/docs/5.3/collections#method-push

更新 5.8 参考:https://laravel.com/docs/5.8/collections#method-push

$users = User::find(1);

$user->objectName = " Value ";

如果您只需要按 eloquent 推入集合中的另一个对象,那效果很好。