jon
jon

Reputation: 1581

How to make dynamic app settings data accessible to other classes in laravel?

I'm using Laravel framework. On every request, I need to get some settings data from a DB (based on subdomain) and have that data available to the other classes in the app. I am currently running a middleware to get the data and store it as a session so that it is accessible to other classes.

Question: What is the Laravel best practise for doing the above?

I appreciate this may lead to opinionated answers, however I think it is really important for a developer that wants to work with others to understand best practises and approaches - even if they are up for debate.

Upvotes: 0

Views: 81

Answers (1)

Dhairya Lakhera
Dhairya Lakhera

Reputation: 4808

As per your requirement you need a single instance through out the application. Check this out Binding Instances

Create you class that fetch settings from DB

class SomeGlobalSettingService
{
    public function settings()
    {
        return 'some DB data using DB facade or model whatever';
    }
}

Now register the above class in AppServiceProvider

/**
 * Register any application services.
 *
 * @return void
 */
public function register()
{
    $this->app->instance(SomeGlobalSettingService::class, new SomeGlobalSettingService());
}

Now access this data anywhere in other classes. It will return only a single instance.

app(SomeGlobalSettingService::class);

Upvotes: 2

Related Questions