We have almost the same situation. Here is our approach:
Service provider
We have a ServiceProvider called BootTenantServiceProvider that loads the tenant in a regular HTTP / Console request. He expects an environment variable to exist under the name TENANT_ID . At the same time, it will download all the relevant configurations and configure a specific tenant.
Value with __sleep () and __wakeup ()
We have a BootsTenant trait that we will use in our queue tasks that looks like this:
trait BootsTenant { protected $tenantId; public function __sleep() { $this->tenantId = env('TENANT_ID'); return array_keys(get_object_vars($this)); } public function __wakeup() {
Now we can write a queue job that uses this feature. When a job is serialized in a queue, the __sleep() method will store the tenantId locator locally. When unesterized, the __wakeup() method will restore the environment variable and start the service provider.
Queue Jobs
Our jobs in the queue just have to use this attribute:
class MyJob implements SelfHandling, ShouldQueue { use BootsTenant; protected $userId; public function __construct($userId) { $this->userId = $userId; } public function handle() {
Conflict with SerializesModels
The SerializesModels attribute that Laravel includes includes its own __sleep and __wakeup . I did not quite understand how both of these traits work together or even if it is possible.
At the moment, I am sure that I never provide a full-fledged Eloquent model in the constructor. You can see in my example the work above. I only store identifiers as attributes of a class, not complete models. I have a handle() method for fetching models at run time. Then I don't need the SerializesModels trait at all.
Use queue: listen instead of --daemon
You need to start your queue employees using queue:listen instead of queue:work --daemon . The former loads the framework for each job into the queue, the latter stores the boot infrastructure loaded into memory.
At the very least, you need to do this if your tenant's boot process needs a new frame load. If you can load multiple tenants in a row by reading the rewrite of the configurations for each, then you can quit queue:work --daemon just fine.