Search code examples
laravellaravel-collection

how to push object inside array laravel php


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


Solution

  • 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']);