Search code examples
phplaravelpusherservice-providerbroadcasting

Laravel: dynamic configuration for Pusher


I am trying to make the configuration for Pusher in my Laravel app (SaaS) dynamic. Basically I want to store different Pusher configs for different accounts. And call the corresponding config based on the user.

I have tries to change the config in runtime using config()->set('services.pusher.xxx', 'yyyy'), but this doesn't work at any level of the framework, event in a custom ServiceProvider.

I found Laravel's BroadcastManager and tried to override the createPusherDriver() so that I could create a custom instance of PusherBroadcaster with the user's config, but I am not sure how to do that or where to put it!

What is the best-practice/standard way to do that?


Solution

  • I've been using a setup like this in one of my own projects, to set a custom mail config:

    NOTE: Your mileage may vary due to the order in which service providers are loaded in your app.

    Create a serviceprovider like app\Providers\ConfigProvider.php

    public function boot()
    {
        $this->app->booted(function () {
            $shouldSetCustomConfig = true;
            // Set config values from database.
            if($shouldSetCustomConfig) {
                config([
                    'mail.host' => Config::get('mail.host'),
                    'mail.port' => Config::get('mail.port'),
                ]);
            }
        });
    }
    
    • The $this->app->booted() is a simple callback that gets called after the application has been booted. This might not always work correctly because I've seen various packages that use this callback too to do various stuff. When this is the case, the order of registration matters. Note that it is not required to use this callback. One might simply call the config(['key' => 'newval']) directly and it could work as intended.
    • The service provider above should be loaded BEFORE the provider you are setting configuration for. In the example above it would be the Illuminate\Mail\MailServiceProvider::class. This should make sure the correct config is loaded.