Super Quick Tutorial: Using Laravel Configurations stored in the Database

The Problem / Situation

You want to store some configurations from the UI, so that your system can be used to do something at runtime. Maybe it’s rate limits, or site titles, or something.

The Super Quick Solution

Build a storage mechanism (probably a migration and model) to store your tables. I’ll assume you’ve created a model called Option and have given it 2 fields, option and value similar to WordPress.

In your AppServiceProvider or some other Service Provider that is going to be called; put the following code.

if (Schema::hasTable('options')) {
    foreach(Option::all() as $option){
        Config::set($option->option, $option->value);
    }
}
  1. The if statement ensures the options table exists
  2. The foreach statement grabs the models/records from the options table
  3. The Config::set line take the option (like app.name) and sets the config, through the Laravel Config facade, as the value from the model

You will also want the following namespace import declarations

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Schema;
use Your\Model\Namespace\Option;

Also Consider

  1. Not everything is safe to be stored in plaintext, you might want to use Laravel’s encryption, depending on what you’re storing, to encrypt/decrypt the values you’re saving.
  2. You might want to invoke some kind of autoloading on your model, as the contents of your options table theoretically could get quite large
  3. You might want to save the database query from being executed every time the app is hit. If that’s the case, try Caching the results, but be sure to expire your cache one way or another, so that changes work properly

I'd love to hear your opinion on what I've written. Anecdotes are always welcome.

This site uses Akismet to reduce spam. Learn how your comment data is processed.