Is it possible to do this? I got a function that takes these parameters.
Upon the first time it's called it will create all possible settings that are defined by a JSON file and save them to the database. Important column here is meta, which is string column but saves json values.
Once data has been saved to the database, meta values do not need to be modified anymore and we do not need to send them from UI back to the server when we want to save. What will happen bellow if $meta is null? It will set the meta column to null as well. Is there an elegant way to tell laravel not to update the column if the value that comes in is null, so it keeps the old values?
public function saveSetting($section, $parent, $key, $value, $type = 'string', $meta)
{
if(is_array($value) || is_object($value)) {
$type = 'json';
$value = json_encode($value);
}
$setting = $this->settings()->updateOrCreate(
['theme_id' => $this->id, 'section' => $section, 'key' => $key],
['section' => $section, 'parent_id' => $parent, 'key' => $key, 'value' => $value, 'type' => $type, 'meta' => $meta]
);
return $setting;
}
Right now only solution I think of is where I use an if to see if meta is set, something like this:
public function saveSetting($section, $parent, $key, $value, $type = 'string', $meta)
{
if(is_array($value) || is_object($value)) {
$type = 'json';
$value = json_encode($value);
}
if(isset($meta)) {
$setting = $this->settings()->updateOrCreate(
['theme_id' => $this->id, 'section' => $section, 'key' => $key],
['section' => $section, 'parent_id' => $parent, 'key' => $key, 'value' => $value, 'type' => $type, 'meta' => $meta]
);
} else {
$setting = $this->settings()->updateOrCreate(
['theme_id' => $this->id, 'section' => $section, 'key' => $key],
['section' => $section, 'parent_id' => $parent, 'key' => $key, 'value' => $value, 'type' => $type]
);
}
return $setting;
}
Is there any better way to skip updating meta?
This is how code that calls saveSetting function looks like:
foreach ($section as $key => $setting) {
$theme->saveSetting($sectionKey, $sectionSetting->id, $key, $setting['value'], $setting['type'], null);
}
meta is set to null, since we already have meta in the database and our UI does not need to send it to the server upon user pressing save. We only send to server data user actually can modify.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire