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);
}
}
- The
if
statement ensures theoptions
table exists - The
foreach
statement grabs the models/records from theoptions
table - The
Config::set
line take theoption
(likeapp.name
) and sets the config, through the Laravel Config facade, as thevalue
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
- 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.
- You might want to invoke some kind of autoloading on your model, as the contents of your
options
table theoretically could get quite large - 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