导致"Maximum function nesting level"错误的用户的Laravel全局范围



我目前有几个用户roles

  • 管理
  • 所有者
  • 经理

我还有一个模型叫Company。所有其他模型(包括User模型(都具有company_id属性。我想创建一个全局作用域,该作用域将所有作用域限定为company_id,但具有Admin角色的用户除外。管理员应该能够看到所有内容,无论模型适用于哪家公司。

我在访问应用程序中的任何页面时收到以下错误:

达到最大函数嵌套级别"256",正在中止!

这是我的范围代码:

<?php
namespace AppScopes;
use IlluminateDatabaseEloquentScope;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentBuilder;
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);
        }
    }
}

以下是我如何应用范围的示例:

<?php
namespace App;
use AppScopesCompanyScope;
use AppTraitsColumnFillable;
use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser 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('AppCompany');
    }
}

这是我使用示波器的另一个模型:

<?php
namespace App;
use AppScopesCompanyScope;
use AppTraitsColumnFillable;
use IlluminateDatabaseEloquentModel;
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('AppCompany');
    }
}

我猜当 Laravel 调用 auth() 函数时它会创建一个无限循环?如何在不使用本地作用域的情况下防止这种情况?

我设法通过将条件语句移动到 boot 方法而不是作用域类中来解决此问题:

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

最新更新