Laravel Facades – Passing parameter to __construct()

Tags: , , ,



If I am creating a Facade, and I want to pass parameters before it becomes instantiated, what do I do?

Answer

The facade’s underlying service is resolved through the IoC container, so all you have to do is bind it correctly.

Create a Service Provider, and pass in whatever you want:

use IlluminateSupportServiceProvider;

class FooServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->bind('foo', function()
        {
            return new Foo('pass whatever you want');
        });
    }
}

Don’t forget to load the service provider in your app’s config array.

Then use that bound key in your facade:

class Bar extends Facade {

    protected static function getFacadeAccessor() { return 'foo'; }

}


Source: stackoverflow