Landlord icon indicating copy to clipboard operation
Landlord copied to clipboard

Multitenant not working with User model

Open subhra44 opened this issue 7 years ago • 4 comments

Multi tenant is not working with User Model. But it is working fine with all other models.

App/User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use HipsterJazzbo\Landlord\BelongsToTenants;

class User extends Authenticatable
{
    use Notifiable;
    use EntrustUserTrait;
    use BelongsToTenants;
    
     /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'organization_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

subhra44 avatar Dec 17 '17 16:12 subhra44

@ subhra44, The SessionGuard may load your user from database, I guess you want to resolve tenant from your user table, at this moment , you user model try to scope your user table, but you don't set tenant yet ,so your user model is differed , you should boot the differed models after login , that is purpose of the applyTenantScopesToDeferredModels method I guess.

videni avatar Mar 14 '18 09:03 videni

@subhra44 is the trait BelongsToTenants not scoping the users?

gkarugi avatar Mar 14 '18 22:03 gkarugi

Can anyone suggest where the applyTenantScopesToDeferredModels() function should be called? I find the only place it works is before each user model call inside the controller. i.e

Landlord::applyTenantScopesToDeferredModels();
$users = User::all();

This does mean it needs to be repeated quite a lot though. Any ideas why it does not work inside the UserController constructor?

booni3 avatar Apr 18 '18 15:04 booni3

I know this is an old issue, but I ran into this exact issue and this post helped me come up with a fairly good solution.

We have some middleware that is responsible for tenancy. It is the code that eventually calls \Landlord::addTenant if we decide it's a valid user.

If we call addTenant, we also call Landlord::applyTenantScopesToDeferredModels() right after.

This seems to be a solution that seems to work across the entire system without spreading this across all our controllers. But it means you have to push your logic up from the controllers to middleware, which may not be a simple change to make to an existing system, but something to consider for new systems.

randarp avatar Oct 31 '18 03:10 randarp