How to unset scoped instances from the DI Container in laravel?

Updated: Feb 10, 2025

How to unset scoped instances from the DI Container in laravel?

In Laravel, the Dependency Injection (DI) container is used to manage and resolve dependencies between different parts of your application. When you define a scoped instance in Laravel, it means that the container will only create a new instance of that class when the given key is requested for the first time within a single request cycle.

However, there might be situations where you want to unset or remove a scoped instance from the DI container before the end of the request cycle. Here's how you can do it:

  1. First, you need to get a reference to the scoped instance from the container. You can do this by calling the make method on the container with the key that was used to register the scoped instance.
$instance = app()->make('your-scoped-instance');
  1. Once you have a reference to the instance, you can remove it from the container by calling the instance method on the container with the same key, and passing the instance as an argument.
app()->instance('your-scoped-instance', null);

By passing null as the argument, you are effectively removing the instance from the container.

  1. After removing the instance from the container, you should release the memory used by the instance to prevent memory leaks. You can do this by calling the release method on the instance.
$instance->release();

Here's an example of how you can use these methods to unset a scoped instance from the DI container:

// Get a reference to the scoped instance
$instance = app()->make('your-scoped-instance');

// Remove the instance from the container
app()->instance('your-scoped-instance', null);

// Release the memory used by the instance
$instance->release();

Keep in mind that unseting a scoped instance from the container will only affect the current request cycle. The next time the same key is requested, a new instance of the class will be created.