#Executing a delayed callback in the correct Tenant context
If you need to define a callback that will be executed in the correct Tenant context every time it is called, you can use the Tenant's callback method.
A notable example for this is the use in the Laravel scheduler where you can loop through all the tenants and schedule callbacks to be executed at the given time:
To execute landlord code, from inside a tenant request, you can use the method execute on Spatie\Multitenancy\Landlord.
Here is an example where we will first clear the tenant cache, and next, the landlord cache:
// it will clear the tenant cache
// it will clear the landlord cache
Landlord::execute(fn () => Artisan::call('cache:clear'));
Inside the closure passed to execute, the landlord is made active by forgetting the current tenant.
When performing testing and using the DatabaseTransactions trait, the default setup in Laravel requires changes to ensure that the transactions are performed on the Tenant connection. Accordingly, the default TestCase.php file may be updated as below:
In case a user login is performed using the Auth facade in the setUp method on a test, the tenant switching will not happen automatically. Accordingly, the setUp method above may be updated as below to ensure that the required tenant has been set (using the first Tenant as an example below)