Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 save json to database

Tags:

json

php

laravel

help me with save json to db. Table field type - text. I have Model with cast array

class Salesteam extends Model 
{
    protected $casts = [        
        'team_members' => 'array'
    ];
}

I want get json like this {"index":"userId"} and store it to db. Example:

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

I have Salesteam Model and 'team_members' column in db to saving all user id's belong to this team. My code find team by id, get all 'team_members' attribute and add new user to this team. I want store all users in json format and incrementing index when add new user id.

Salesteam attributes:

"id" => 20
"salesteam" => "Admin"
"team_leader" => 0
"invoice_target" => 884.0
"invoice_forecast" => 235.0
"team_members" => "[1,66,71]"
"leads" => 0
"quotations" => 0
"opportunities" => 0
"notes" => ""
"user_id" => 1
"created_at" => "2017-09-22 09:13:33"
"updated_at" => "2017-09-22 13:10:25"
"deleted_at" => null

Code to add new user to team:

$salesTeam = $this->model->find($salesTeamId);
$teamMembers = $salesTeam->team_members;
$teamMembers[] = $userId;
$salesTeam->team_members = $teamMembers;
$salesTeam->save();

But it stores to db array and without index

"team_members" => "[1,34,56]"

From Laravel documentation - Array & JSON Casting "array will automatically be serialized back into JSON for storage"

Where i'm wrong?

like image 949
tosky Avatar asked Sep 22 '17 12:09

tosky


2 Answers

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

like image 165
rummykhan Avatar answered Nov 02 '22 10:11

rummykhan


Simply use

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

That should do be all.

like image 23
omar jayed Avatar answered Nov 02 '22 10:11

omar jayed