laravel-tenants
laravel-tenants copied to clipboard
How to deal with querying code at console and seeders?
I've found that querying models on seeders are using using default root tenant so behaviour is unexpected.
$tenants = app('rinvex.tenants.tenant')->all();
foreach ($tenants as $tenant) {
$all_users = User::withAllTenants($tenant)->get(); <-- Not working, gets main domain users
$all_users = User::withAnyTenants($tenant)->get(); <-- Not working, gets main domain users
$all_users = $tenant->entries(User::class)->get(); <-- Not working, gets main domain users
}
I finally made my own trait that works thanks to "withoutGlobalScopes":
trait ForTenant
{
public function scopeForTenant($builder, $tenant)
{
return (new static())->newQuery()->withoutGlobalScopes(['tenantable'])->whereHas('tenants', function ($builder) use ($tenant) {
$builder->where($key = $tenant->getKeyName(), $tenant->{$key})->where('is_active', true);
});
}
}
Could there be a better solution for this?
A) withAnyTenantsWithoutGlobalScopes methods?
B) initialize withAnyTenant methods with withoutGlobalScopes when application running outside request cycle?
C) I still find strange I am the first to deal with this issue and there must be something wrong with my setup...
3 tenants with 3 subdomains created with a seeder:
- domain.org
- b.domain.org
- c.domain.org
Config/app.php entry:
'domains' => [
env('MULTITENANT_DOMAIN', 'another.org') => [],
],
and at .env file:
MULTITENANT_DOMAIN=domain.org