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?
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With