Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

grubi's avatar
Level 7

Laravel API, Nuxt 3 and Multitenant

I have set up an environment with a Laravel API as backend and a Nuxt 3 App as frontent. Authentication works fine after some issues with CORS. My next step is to add multiple tenants. As in the course of Kevin McKee descripted I added a Listener which saves the tenant_id of the user in a session and a Scope, which adds the tenant_id to the queries. Everything works fine if I add a static tenant_id (like 1 or 2) to the builder. But as soon as I read the tenant_id out of the session like below, the login on the nuxt-side doesn't work anymore a 422 on login and next a 405 on login.

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Facades\Log;

class TenantScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     */
    public function apply(Builder $builder, Model $model): void
    {
         // Log::alert("Session TenantScope: " . session()->get('tenant_id'));

        $tenant_id = session()->get('tenant_id');

        Log::alert($tenant_id);

        $builder->where('tenant_id', session()->get('tenant_id'));
    
    }
}

Does anybody has an idea why the builder doesn't work, when I add the tenant_id out of the session? Logging the tenant_id out of the session works fine in the same code section.

0 likes
2 replies
LaryAI's avatar
Level 58

The issue seems to be with the way you are accessing the session in the TenantScope class. Instead of accessing the session directly using session()->get('tenant_id'), you should use the $tenant_id variable that you have already assigned the session value to.

Here's an updated version of the apply method in the TenantScope class:

public function apply(Builder $builder, Model $model): void
{
    $tenant_id = session()->get('tenant_id');

    $builder->where('tenant_id', $tenant_id);
}

By using the $tenant_id variable, you ensure that the same value is used consistently throughout the method.

Make sure to update your code accordingly and test if the issue is resolved.

Please or to participate in this conversation.