2

i did query from db and return array

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

now i am trying to add object inside $games array like this

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

please explain Thank you

sid heart
  • 1,140
  • 1
  • 9
  • 38

1 Answers1

3

Because you pushed an array, so it is adding array.

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

Pushing the object like this:

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

or this way:

$games = $games->push((object)['name' => 'Game1', 'color' => 'red']);
Andy Song
  • 4,404
  • 1
  • 11
  • 29
  • i don't want to save to db i just want to add inside array variable – sid heart Sep 01 '20 at 22:51
  • @sidheart there is nothing related saving into db? where did you get it from? – Andy Song Sep 01 '20 at 22:53
  • @sidheart using eloquent model does not mean saving into db. – Andy Song Sep 01 '20 at 22:54
  • That is the problem i am facing that i have collection get from db and i want to add 2 more object inside array variable that i can use it like `$game->name` later – sid heart Sep 01 '20 at 22:57
  • @sidheart my answer did exactly what you wanted, the two solutions I provided are not updating db at all. I do not understand what are you worrying about. – Andy Song Sep 01 '20 at 23:00
  • ohh thanks this `$games = $games->push((object)['name' => 'Game1', 'color' => 'red']);` works fine thank you – sid heart Sep 01 '20 at 23:00