简体   繁体   中英

Laravel global scope for users causing “Maximum function nesting level” error

I currently have a few user roles :

  • Admin
  • Owner
  • Manager

I also have a model called Company . All other models (including the User model) have a company_id attribute. I want to create a global scope which scopes everything to the company_id EXCEPT for users with the Admin role. Admins should be able to see everything, regardless of which company the model is for.

I am getting the following error when visiting any page in my application:

Maximum function nesting level of '256' reached, aborting!

Here is my scope code:

<?php

namespace App\Scopes;

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

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

Here is an example of how I am applying the scope:

<?php

namespace App;

use App\Scopes\CompanyScope;
use App\Traits\ColumnFillable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable, ColumnFillable;

    protected $hidden = ['password', 'remember_token'];

    public static function boot()
    {
        parent::boot();

        static::addGlobalScope(new CompanyScope);
    }

    public function company()
    {
        return $this->belongsTo('App\Company');
    }
}

Here is another model I am using the scope on:

<?php

namespace App;

use App\Scopes\CompanyScope;
use App\Traits\ColumnFillable;
use Illuminate\Database\Eloquent\Model;

class Lead extends Model
{
    use ColumnFillable;

    protected $casts = [
        'data' => 'array',
    ];

    public static function boot()
    {
        parent::boot();

        static::addGlobalScope(new CompanyScope);
    }

    public function company()
    {
        return $this->belongsTo('App\Company');
    }
}

I'm guessing it is creating an endless loop when Laravel calls the auth() function? How do I prevent this without using local scopes?

I managed to fix the issue by moving the conditional statement into the boot method rather than inside the scope class:

    if (auth()->check() && auth()->user()->role != 'Admin') {
        static::addGlobalScope(new CompanyScope);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM