首页 > 解决方案 > 如何在数组laravel php中推送对象

问题描述

我从数据库查询并返回数组

$games = Game::where('admin_id', $user->id)->where('active', true)->get();

现在我正在尝试$games像这样在数组中添加对象

$games->push(['name' => 'Game1', 'color' => 'red']); //its adding array instead object

请解释 谢谢

标签: laravellaravel-collection

解决方案


因为你推了一个array,所以它正在添加数组。

// here, you are pushing the array so you get the array.
['name' => 'Game1', 'color' => 'red']

像这样推送对象:

$games = $games->push(new Game(['name' => 'Game1', 'color' => 'red']));

或者这样:

$games = $games->push((object)['name' => 'Game1', 'color' => 'red']);

推荐阅读