To achieve the desired functionality of updating only specific subkeys of the config field in the database, you can use Laravel's ->json() method to update JSON columns. Here's how you can adapt your code to handle this:
- Check if the
configkey exists in the request body. - Merge the existing
configdata with the new data from the request body. - Update the
configfield in the database with the merged data.
Here's the updated code:
$fieldsToUpdate = [];
foreach ($body->payload as $key => $value) {
if (in_array($key, ['input_bandwidth', 'output_bandwidth', 'config'])) {
if ($key === 'config' && is_array($value)) {
// Fetch the existing config from the database
$existingConfig = $port->config ?? [];
// Merge the existing config with the new values
$mergedConfig = array_merge($existingConfig, $value);
// Add the merged config to the fields to update
$fieldsToUpdate[$key] = $mergedConfig;
} else {
if ($value) {
$fieldsToUpdate[$key] = $value;
}
}
}
}
$infrastructure = Infrastructure::firstOrCreate([
'name' => $body->payload->infrastructure_name,
]);
$port = Port::updateOrCreate([
'name' => $body->payload->name,
'infrastructure_id' => $infrastructure->id,
], $fieldsToUpdate);
Explanation:
-
Check for
configkey: The code checks if theconfigkey is present in the request body and if it is an array. -
Fetch existing config: It fetches the existing
configdata from the database. If theconfigfield is null, it initializes it as an empty array. -
Merge configs: It merges the existing
configdata with the new data from the request body. -
Update fields: It adds the merged
configdata to the$fieldsToUpdatearray. -
Update or create: Finally, it updates or creates the
Portrecord with the updated fields.
This approach ensures that only the specified subkeys in the config field are updated, while the other subkeys remain unchanged.