Tenant aware function returns Database connection [tenant] not configured

371 Views Asked by At

In Laravel 8, using Stancl's TenancyForLaravel 3 package, I want to run tenant aware code from my central domain. This code should find the user in the tenant database and return it.

I've this code. <?php

    namespace App\Http\Controllers\Api;
    
    use App\Http\Controllers\Controller;
    
    use App\Models\Tenant;
    use App\Models\User;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Hash;
    
    class MasterAuthController extends Controller
    {
        public function login(Request $request)
        {     
            $tenant = Tenant::find('tenant1');
            $user = $this->GetUser($tenant);
            return $user;
    
        }
    
        public function GetUser(Tenant $tenant)
        {
            return $tenant->run(function($tenant) {
                $user = \App\Models\User::where('email', '[email protected]')->first();
                return $user;         
            });
        }
    
    }

The user exists and this works in Laravel Tinker!, but in the application it returns this error:

"message": "Database connection [tenant] not configured.",
    "exception": "InvalidArgumentException",

What am I doing wrong?

2

There are 2 best solutions below

0
Alex Angelico On

Fixed it, the problem was, "You should do everything tenant-related inside the tenant context. And only return the actual data (not models) from $tenant->run()." https://github.com/archtechx/tenancy/issues/808

So,

public function GetUser(Tenant $tenant)
        {
            return $tenant->run(function($tenant) {
                $user = \App\Models\User::where('email', '[email protected]')->first();
                return $user;   // you cannot return the model      
            });
        }

must be

public function GetUser(Tenant $tenant)
        {
            return $tenant->run(function($tenant) {
                $user = \App\Models\User::where('email', '[email protected]')->first();
                return $user->name; // return actual data        
            });
        }
0
Emad Uddin On

Try This way -

public function GetUser(Request $request,Tenant $tenant)
    {
        return $tenant->run(function () use ($request) {
            return User::where('email', $request->email)->first()->toArray();
        });
    }

$tenant->run() only return the actual data not models. So, Just add ->toArray() after the query for solved the problem.