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

ssquare's avatar

Best way to cache settings value in laravel shared hosting

I have an app and I have table settings, to get these values I have created this in appServiceProvider

 config(['settings' => Setting::first()]);

Instead of querying this on every request from laravel database, is there any way to cache these values? Or, I don't need to worry about it because config itself does this for us? Or, is there any better way to deal with this situation.

I have some values like appName, admin email, social handle, and stuff like that in the settings table. What would be my best bet to deal situation like this?

0 likes
1 reply
martinbean's avatar
Level 80

@ssquare You could create a SettingsRepository that encapsulates the caching logic. Your application can then call a method on this repository and retrieve the settings and not care if the settings came from the cache or if they came from the database:

class SettingsRepository
{
    public function all()
    {
        return Cache::rememberForever('settings', function () {
            return Setting::pluck('value', 'key');
        });
    }

    public function get($key, $default = null)
    {
        return $this->all()->get($key, $default);
    }
}

Now, you can type-hint this repository where ever you need settings in your application:

class SomeController extends Controller
{
    protected $settings;

    public function __construct(SettingsRepository $settings)
    {
        $this->settings = $settings;
    }

    public function someAction()
    {
        $adminEmail = $this->settings->get('adminEmail');

        // Do something with $adminEmail...
    }
}

If you do cache settings, just be sure to clear the cache when you add/edit/remove a setting value from the database.

Please or to participate in this conversation.