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

asoftware's avatar

Add Global Scope but only for API routes

I have a global scope that attaches to a model and adds an additional where clause to my database queries; however, it gets this information to add to the where clause from from the session variables.

I would like to take advantage of this global scope on my API calls, but obviously do not have access to session variables. Is there a way to detect that the API route is calling and do some modification to the global scope to make this work for the API routes? Below is my global scope its for Tenant... learned this from one of the Laracasts multi-tenant videos

class TenantScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        if(session()->has('tenant_id'))
        {
            $builder->where('tenant_id', '=', session()->get('tenant_id'));
        }
    }
}

0 likes
2 replies
bugsysha's avatar

When I've tried to make things like this automatic, I've always regretted it later. Either it was not obvious and it caused me to debug things longer or I had to change the logic because business rules changed. I would suggest that you keep it at the perimeter of your app and very explicit.

1 like
martinbean's avatar

@seanworks Dont. Like @bugsysha says, it just ends up causing more problems than it solved. I ended up rewriting a SaaS from scratch because I did this.

Your models shouldn’t know anything about the request, including session data. Instead, use local scopes where you pass the tenant in, or query your models through relations on a tenant model if that’s the “root”.

Please or to participate in this conversation.