I wanted to know what the best way is to store single data values in a database. Values you only need one field of.
I have a couple of ideas.
Which one is the best way? Or might there even be better ways?
Or is it just easier to keep single data values as static data on the webpage?
At my current job we use a separate settings
table for that, with two columns: key
and value
. And then there's a simple function to retrieve or save a setting:
function setting($key, $value = null){
$setting = DB::table('settings')->where('key', $key)->first();
if(is_null($value)){
return $setting->value ?? null;
}
if(isset($setting)){
$setting->value = $value;
}else{
$setting = $setting ?: new stdClass();
$setting->key = $key;
$setting->value = $value;
}
DB::table('settings')->insertOrReplace((array) $setting);
return true;
}
It is used like so:
$phone = setting('phone'); // Get the phone setting
$url = setting('url', 'http://example.com'); // Set url setting