The key points regarding using a singleton with the configuration repository instance in Laravel are:
1. When registering a singleton in the service container, you should pass a callback instead of the actual instance of the configuration repository. This ensures the configuration repository is only resolved once, even if it's requested multiple times. [1][2]
php
// Instead of...
$this->app->singleton(Service::class, function ($app) {
return new Service($app['config']);
});
// Do...
$this->app->singleton(Service::class, function ($app) {
return new Service(fn() => Container::getInstance()['config']);
});
2. Alternatively, you can use the `config()` helper function inside the service class instead of injecting the configuration repository. This achieves the same result of only resolving the configuration repository once. [1]
php
// Instead of...
$this->app->singleton(Service::class, function ($app) {
return new Service($app['config']);
});
// Do...
$this->app->singleton(Service::class, function ($app) {
return new Service(fn() => config());
});
3. When running on Laravel Octane, singletons that are resolved during the application bootstrapping will persist between requests. However, singletons resolved during request handling will be registered in a sandbox container that is destroyed after handling the request. [1]
4. To ensure singletons persist between requests on Octane, you can either resolve them in your service providers or add them to the `warm` array in the Octane configuration file. [1]
php
// In the Octane configuration file
'warm' => [
...Octane::defaultServicesToWarm(),
Service::class,
],
5. If you have a package that registers and resolves a singleton inside a service provider, and you want to flush that instance before every request, you can add it to the `flush` array in the Octane configuration file. [1]
php
// In the Octane configuration file
'flush' => [
Service::class,
],
In summary, when using singletons with the configuration repository in Laravel, it's important to pass a callback instead of the actual instance to ensure the configuration repository is only resolved once. This is especially crucial when running on Laravel Octane to ensure singletons persist as expected between requests.
Citations:[1] https://divinglaravel.com/laravel-octane-bootstrapping-the-application-and-handling-requests
[2] https://stackoverflow.com/questions/62870556/how-this-app-singleton-works-in-laravel
[3] https://laravel.com/docs/11.x/container
[4] https://www.youtube.com/watch?v=yg1qOom6YuE
[5] https://github.com/laravel/ideas/issues/2487