Home > database >  How to update a json column of a table in laravel
How to update a json column of a table in laravel

Time:06-02

I have below JSON values in the toys columns of the account table

{
   "truck":{
      "qty":10,
      "price":53
   },
   "doll":{
      "qty":15,
      "price":15
   }
}

Now I wantt add new values {"animals":{"qty":1,"price":4},"stickers":{"qty":12,"price":12}} to this. I have tried below method

    $new_toys = [
       'animals'  => ['qty' => 1, 'price' => 4],
       'stickers' => ['qty' => 12, 'price' => 12]
    ];
    $old_tyoys = $account->toys;
    array_push($old_tyoys, $new_toys);
    $account->toys = $old_tyoys;
    $account->save();

But this will update the column as below

{
   "truck":{
      "qty":10,
      "price":53
   },
   "doll":{
      "qty":15,
      "price":15
   },
   "0":{
      "animals":{
         "qty":1,
         "price":4
      },
      "stickers":{
         "qty":12,
         "price":12
      }
   }
}

But I want it as below

{
   "truck":{
      "qty":10,
      "price":53
   },
   "doll":{
      "qty":15,
      "price":15
   },
   "animals":{
      "qty":1,
      "price":4
   },
   "stickers":{
      "qty":12,
      "price":12
   }
}

What do I need to change in the code? Thanks

CodePudding user response:

Replace array_push($old_tyoys, $new_toys); with collect($account->toys)->merge($new_toys)->all();

So your method code would become

$new_toys = [
       'animals'  => ['qty' => 1, 'price' => 4],
       'stickers' => ['qty' => 12, 'price' => 12]
    ];

$merged = collect((array)$account->toys)->merge(new_toys)->all();

//Or

$merged = array_merge((array) $account->toys, $new_toys);

$account->toys = $merged;
$account->save();

CodePudding user response:

That's because you're using array_push to aggregate the two objects, and internally it adds your second parameter as a value assigned to a numeric index 0. Try using array_merge.

  • Related