1 month ago

Larravel singleton is not working properly

Posted 1 month ago by hassanrezay21

We're trying to register a singleton e.g.

$this->app->singleton('blah', function ($app, $options) {
    return $app->makeWith(Something::class, $options);

within the construct of Something::class we logger('started')

We then make the class via the container in a controller e.g.

$something = app()->makeWith('blah', ['x' => 'y'])

We check the log, and you can see the started

Then elsewhere we try to pull it back out the container e.g.

$instance = resolve('blah');

However the log shows another started

This would suggest that container is not returning the same instance as the construct is executed twice.

This is possibly because when we call resolve we're not passing in the same options that it was instantiated with.

If so, how can we get around this without setting a static variable somewhere?

Please sign in or create an account to participate in this conversation.