Search code examples
arraysjsondatabasemodel

Storing single data values in the database


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.

  1. Storing all fields in a single_data_table with a id, key and value column.
  2. Storing it as a json object in the database.
  3. Storing it as an array in the database.

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?


Solution

  • 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