Search code examples
phpmysqllaravelmulti-tenant

Access the data from Central DB inside tenant domain and vice versa Stancl/Tenancy


Description

Is there any way to switch the DB environment in Stancl/Tenancy module? As I earlier worked with some other tenancy modules, I use to switch the environment when I want to access some resources from the central domain inside the tenants and vice versa.

Why this should be added

I was trying to get the plans and features for the tenants, and want to get some more data from the central domain (DB). for eg, I have named subscriptions and plans table both for the tenants and central users, when I try to fetch the subscription of the tenant user from the central domain it is returning the data from the tenant DB.

namespace App\Helpers;
use App\Models\System\Admin\Subscription;
 public static function checkTenantPlan()
    {
        // Find the tenant
        // get the tenantId and find that
        $tenant_user_id = tenant()->user_id;
        // Find the subscription of the tenant User
        $subscription = Subscription::where('user_id', $tenant_user_id)
                        ->orderBy('created_at', 'desc')
                        ->first();
        return $subscription->plan(); //returning the data from the current tenant db
        
    }

Solution

  • It has been fixed in a new release. https://github.com/stancl/tenancy/releases/tag/v3.3.0

    $tenant->run(function ($tenant) {
        return User::all();
    });
    
    tenancy()->central(function ($tenant) {
        return User::all();
    });