Ad

Saving Single Data Values Into Database Using Laravel

- 1 answer

I'm getting stuck at the point on a Laravel project where i want to save single data values, for example on a contact page. I just want to save one phone number and location, which the user can edit (not adding more of them). A lot of people tell me to keep using models although in my eyes they're ment for repeating content, like posts and users. Is there an api/Laravel library that allowes me to store single data in like a json object within a database table?

Ad

Answer

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
Ad
source: stackoverflow.com
Ad