hipsterjazzbo / Landlord

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

Nested Resources don't seem to work #55

Closed illmatic closed 7 years ago

illmatic commented 7 years ago

I have nested resources for Account -> has many Templates I added Landlord to my Account controller and when I checked the DB log, I see the tenant condition added. When I did the same for the Template Controller, I don't see a check when I find the account. Here is my show code

    public function show($account_id, $template_id)
    {
        DB::enableQueryLog();
        $account = Account::findOrFail($account_id);
        DB::disableQueryLog();
        dd(DB::getQueryLog());

It returns

array:1 [ 0 => array:3 [ "query" => "select * from accounts where accounts.id = ? limit 1" "bindings" => array:1 [] "time" => 0.85 ] ]

My middleware that I confirmed is being passed through is the following

            $tenantId = Auth::user()->id;
            Landlord::addTenant('user_id', $tenantId);

Why would it work in my AccountController but not in my TemplateController. The only difference I see is the nesting.

inctor commented 7 years ago

Because it's not required. If the parent is Tenant Scoped, and the child is referenced on a foreign key, the Scope is not required.

As the child is anyways bound directly to the parent (Account), and you'd "always" access the (Template) from the Account, through the relationship.

If you want the child to also be tenant-scoped, you'd need to use the BelongsToTenant trait on the Template-model as well, and make sure the Template-model is not being booted before the Account model is booted. But as mentioned before, scoping a child, is not strictly required if the parent is scoped.