Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update a json column of a table in laravel

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
   "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

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading