How to make your Laravel queues tenant aware

Mhd Omar Bahra
1 min readJul 8, 2021

Many of us might be working on multi-tenancy projects whether we’re using the DB instance per tenant approach or using a single DB approach both have their advantages and disadvantages. However, dealing with queues in the single DB approach might be frustrating as there are multiple ways to do this.

One way to do so is to pass the tenant id to the constructor of each job, this approach is a little bit frustrating, due to the fact that you need to add

->where(‘tenant_id’, $id)

to all your queries, it’s a little bit redundant if you are using global scopes.

The other approach is to listen to the queues’ events from a ServiceProvider and make all the jobs that need to be tenant aware implementing a special interface as shown below:

Here basically before adding the job to the queue, we are adding the current domain to the job payload, and when the job is being enqueued we’re re-reading the domain from the payload and initializing the tenant for the job.

--

--

Mhd Omar Bahra

I am a Software Engineer interested in Software Architecture and Quality Assurance.