phplaravelfilamentphp

ApplyTenantScopes middleware is run twice in Filament/multi-tenancy


ApplyTenantScopes middleware is run twice resulting in a duplicate query (multi-tenancy). I don't know if this is a bug or am I doing something wrong.

I am having a middleware:

class ApplyTenantScopes
{
    /**
     * Handle an incoming request.
     *
     * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
     */
    public function handle(Request $request, Closure $next): Response
    {

        Category::addGlobalScope(
            fn(Builder $query) => $query->whereBelongsTo(Filament::getTenant()),
        );

        return $next($request);
    }
}

It is registered in the panel provider as per docs:

->tenantMiddleware([
                ApplyTenantScopes::class,
            ], isPersistent: true)

Method "handle" is executed twice on each page, resulting in SQL query:

select * from "categories" where "categories"."unit_id" in (1) and "categories"."unit_id" in (1) order by "categories"."id" asc


Solution

  • Most likely the middleware is registered more than once or that query expression is being applied by another part of your application.

    You can try commenting out that query and see if the where clause is still added to the query.

    Additionally, you can give your anonymous global scopes a name. That should prevent the same scope from being added twice.