hipsterjazzbo / Landlord

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

Multitenant not working with User model #87

Open subhra44 opened 6 years ago

subhra44 commented 6 years ago

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',
    ];
}
videni commented 6 years ago

@ 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.

gkarugi commented 6 years ago

@subhra44 is the trait BelongsToTenants not scoping the users?

booni3 commented 6 years ago

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?

randarp commented 5 years ago

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.