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

fylzero's avatar
Level 67

Global Scope on User model not working.

Trying to implement multi-tenancy using a single db approach. My scope works on everything except when I try to put it on the User model my app blows up. Won't even load. What am I doing wrong here?

CompanyScope...

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class CompanyScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        if (auth()->check()) {
            $builder->where('company_id', auth()->user()->company_id);
        }
    }
}

Code on the user model...

protected static function booted()
{
    static::addGlobalScope(new CompanyScope);
}

I'm just trying to display only users that belong to the current users company_id.

What I'm seeing after adding this...

0 likes
4 replies
fylzero's avatar
Level 67

Based on experimentation, I'm assuming I can't call auth() in the scope / when on the User model, but why?

If I do this, it works as I'd expect...

public function apply(Builder $builder, Model $model)
{
    $builder->where('company_id', 1);
}
fylzero's avatar
fylzero
OP
Best Answer
Level 67

Figured this out... just needed to pass the auth user into the scope and it started working. Also had to isset check the user so registration wouldn't die.

protected static function booted()
{
    $authUser = auth()->user()->company_id ?? null;
    static::addGlobalScope(new CompanyScope($authUser));
}

Found the answer here: https://github.com/laravel/framework/issues/25611

3 likes
fylzero's avatar
Level 67

@ahmedmansoor In case this is helpful, I've since switched to using session for this for optimization as well as simplification.

app/Providers/EventServiceProvider.php

protected $listen = [
    Login::class => [SetCompanyIdInSessionListener::class],
];

app/Listeners/SetCompanyIdInSessionListener.php

public function handle($event): void
{
    session()->put('company_id', $event->user->company_id);
}

app/Scopes/CompanyScope.php

public function apply(Builder $builder, Model $model): void
{
    if (session()->has('company_id')) {
        $builder->where($model->getTable().'.company_id', session()->get('company_id'));
    }
}
1 like

Please or to participate in this conversation.