Laravel 5.4 save json to database Laravel 5.4 save json to database laravel laravel

Laravel 5.4 save json to database


To make a json string like this

{"1":"7","2":"14","3":"25","4":"11"}

In php, you must pass a key, when you're pushing elements to array. e.g.

$teamMembers = [];$teamMembers['1'] = 7;$teamMembers['2'] = 14;...

If you don't make it an associative array, php will consider it as json array when converting to json string..

Tip: You may pass only one key and it will work too.e.g.

$test = [1, 2, 3, 4, 5, 6];$test['10'] = 56;echo json_encode($test);

Output:

"{"0":1,"1":2,"2":3,"3":4,"4":5,"5":6,"10":56}"

PHP-Reference


Simply use

$teamMembers = json_encode($salesTeam->team_members);

That should do be all.


if you get this "[1,34,56]" just do json_decode($team_members)

and you will have this:

array:3 [▼  0 => 1  1 => 34  2 => 56]