I need to update a JSON's some of the nested values using Laravel Eloquent, But didn't get the exact result as I wanted as optimized. The below json needs to be updated frequently. I had a working solution to this, But needs to fine tune the solution.
{
"a": {
"b": 12,
"c": 792,
"d": 45,
"e": {
"1": {
"name": "Guna",
"city": "city1",
"dob": 2000
},
"2": {
"name": "Raj",
"city": "city2",
"dob": 2001
},
"3": {
"name": "Dhamu",
"city": "city3",
"dob": 1985
},
"4": {
"name": "Bhavi",
"city": "city5",
"dob": 1985
}
}
}
}
Tried Code
$c_array=Json::decode($this->company->details, 1);
$c_array['a']['Player'][$p[0]]['st']=$p[1];
$c_array['a']['e'][1]['name'] = 'Bheem';
$c_array['a']['e'][1]['city'] = 'City10';
$c_array['a']['e'][2]['name'] = 'Dhanu';
$c_array['a']['e'][2]['city'] = 'City5';
$this->company()->update(['details' => Json::encode($c_array)]);
The above code is working fine, but the whole json is updated when checked the query. I need to update only the individual keys that needs to be updated.
We can update the code using Query Builder (DB::raw) with the following,
update ultimate_squad set squad=JSON_SET(details,'$.a.e."1".name','Bheem','$.a.e."1".city','City10','$.a.e."2".name','Dhanu','$.a.e."2".city','City5') where c_id=1;