Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mallaury's avatar

Store settings from database into config()

Hello,

I'm looking to store values from my database in my laravel config. I would store for example the site's title, the colors, etc. I would like datas to be loaded in config only if they do not exist yet. When the data is modified, it will be deleted from config() so it will be load again.

Here is the code :

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        if (Schema::hasTable('settings')) {
            if (!Config('settings')) {
                Config::set('settings', \App\Models\Setting::all());
            }
        }
    }
}

Of course I have a model and a table called "Setting". The problem is : every time I load a page, it considers that config('settings') is empty and so it retrieves it from the database. I also tried with a singleton... Do you have any idea why?

0 likes
7 replies
mallaury's avatar
mallaury
OP
Best Answer
Level 2

Ok... I found.

I changed the code by this one :

public function boot()
    {
        if (Schema::hasTable('settings')) {
            if (!Config('settings')) {
                foreach (\App\Models\Setting::all() as $setting) {
                    Config::set('settings.' . $setting->key, $setting->value);
                }
            }
        }
    }

And ran the command to cache the config:

php artisan config:cache
mallaury's avatar

@Niush Thank for the advice. But I am building a very light CMS and I try to do without packages.

Snapey's avatar

@mallaury have you checked that your code is not executed in its entirety on every request?

See tinker session:

~/ > php artisan tinker
Psy Shell v0.10.12 (PHP 7.4.28 — cli) by Justin Hileman
>>> config('settings')
=> null
>>> Config::set('settings.hello','eyup')
=> null
>>> config('settings')
=> [
     "hello" => "eyup",
   ]
>>> quit
Exit:  Goodbye
~/ > php artisan config:cache
Configuration cache cleared!
Configuration cached successfully!
~/ > php artisan tinker      
Psy Shell v0.10.12 (PHP 7.4.28 — cli) by Justin Hileman
>>> config('settings')
=> null
>>> 

caching config does NOT save these added values.

Snapey's avatar

Why not just get the settings directly from the database, and pass them to views with a view composer?

mallaury's avatar

@Snapey Because I do not want to fetch the database each time we load a page.

Please or to participate in this conversation.