hipsterjazzbo / Landlord

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

Doesn't even work. #64

Closed kjdion84 closed 7 years ago

kjdion84 commented 7 years ago

I have a Role model. I've publish the config file, set the model to use the trait, and also made sure that tenant_id exists in the roles table. I've also called Landlord::addTenant('tenant_id', $tenant->id); in my group middleware.

When I dump getTenants() on the page I get:

Illuminate\Support\Collection Object ( [items:protected] => Array ( [tenant_id] => 1 ) )

Well when I run this simple code:

        $roles = Role::all();

        foreach ($roles as $role) {
            echo $role->name.'<br>';
        }

It is echoing the roles that belong to any tenant. This does not even work at all.

genesluna commented 7 years ago

Same problem here.

fourstacks commented 7 years ago

@genesluna & @kjdion84 - have you checked to make sure you're pulling in the BelongsToTenant trait in the models you want to scope (the Role model in the example above?)

I'm using 2.0.5 and I've just set up this simple test as I'm using Landlord in an app I'm working on:

/** @test */
public function setScoping()
{
    $accountOne = factory(Account::class)->create();
    $accountTwo = factory(Account::class)->create();

    \Landlord::addTenant($accountTwo);

    factory(UserProfile::class)->create(['account_id' => $accountOne->id,]);
    factory(UserProfile::class)->create(['account_id' => $accountTwo->id,]);

    $userProfiles = UserProfile::all();

    $this->assertEquals(1, $userProfiles->count());
    $this->assertEquals(2, $userProfiles->first()->id);
}

Which works just as expected (e.g. the test passes) if the trait is in place and fails (showing all UserProfiles) if the trait is removed which sounds like the behaviour you're experiencing

hipsterjazzbo commented 7 years ago

I'm using this package in over a dozen different large production applications and it absolutely does work.

Without more information I can't help you fix this issue, but almost always it winds up being because you need to make sure you're adding tenants before you need them.

S43534 commented 7 years ago

I guess you are using the package Laravel Permission from Spatie. This package boots the Role model in its service provider. If you use a middleware to set the tenant it will not work on the Role model because by this time it is already booted.

Solution: call \Illuminate\Database\Eloquent\Model::clearBootedModels(); before adding the tenant.

See also #61.

Sebastian