Ever had a singleton in your Laravel application that you'd really like access to in a queued job?
Let's take as an example an application with multiple tenants. To keep track of the tenant for the current request,
we have a Tenant
object bound as a singleton in our application. When we dispatch a job to the queue, we want to keep track of the
tenant that the job is for. But how can we do that? We don't want to store the tenant in the job itself, because that will quickly get
repetitive. It would be much better if every job was automatically aware of the tenant that was active at the time of dispatching.
Using this package, we can do exactly that, and it couldn't be simpler!
We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.
You can install the package via composer:
composer require spatie/laravel-queue-aware
To make the queue aware of an object, you can register the object in one of your service provider's boot
methods. We'll use the
Tenant
example from the previous section.
public function boot()
{
QueueAwareFacade::register(
Tenant::class,
fn () => Tenant::current()?->id,
fn ($tenantId) => Tenant::find($tenantId),
);
}
The register
method of the QueueAwareFacade
takes 3 parameters:
- The key of the singleton in the Laravel container (usually the FQCN of the object)
- A closure that returns the information needed to rebuild the singleton
- A closure that is given the data returned in step 2 and returns a new instance of the singleton
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.