hipsterjazzbo / Landlord

A simple, single database multi-tenancy solution for Laravel 5.2+
MIT License
615 stars 138 forks source link

BelongsToTenant not working on user model #80

Closed meta0102 closed 6 years ago

meta0102 commented 6 years ago

hi, i know that there is already an closed issue with the same behavior. no solution is working for me.

Tenant is working on all Models except the User model.

Middleware applied in route

Route::group(['middleware' => ['auth:api','multitenant']], function() {
});

Kernel.php (i've also tried to add the Middleware to the $middleware or api group, same result)

 protected $middlewareGroups = [
        'customuser' => [
            \App\Http\Middleware\ScopeCompany::class,
        ],
    ];

Middleware:

class ScopeCompany
{
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            $companyId = Auth::user()->company_id;
            if($companyId != null) {
                Landlord::addTenant('company_id', $companyId);
            }
        }
        return $next($request);
    }
}

User Model:

class User extends Authenticatable
{
    use Notifiable, HasApiTokens, BelongsToTenants, SoftDeletes;
}

thanks for any help!

meta0102 commented 6 years ago

i fixed this issue by adding Landlord::applyTenantScopes(Auth::user()); to my middleware

class ScopeCompany
{
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            $companyId = Auth::user()->company_id;
            if($companyId != null) {
                Landlord::addTenant('company_id', $companyId);
                Landlord::applyTenantScopes(Auth::user());
            }
        }
        return $next($request);
    }
}
divdax commented 6 years ago

Thank you @meta0102 this also works for me!

@HipsterJazzbo Maybe the documentation should be updated how to setup this package correctly? 😄