【发布时间】:2019-08-14 03:26:30
【问题描述】:
我目前有几个用户roles:
- 管理员
- 所有者
- 经理
我还有一个名为Company 的模型。所有其他模型(包括User 模型)都具有company_id 属性。我想创建一个全局范围,将所有内容都限制在company_id 范围内,但对于具有Admin 角色的用户除外。管理员应该能够看到所有内容,无论模型是针对哪家公司的。
访问我的应用程序中的任何页面时出现以下错误:
已达到“256”的最大函数嵌套级别,正在中止!
这是我的范围代码:
<?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);
}
}
}
这是我如何应用范围的示例:
<?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');
}
}
这是我使用范围的另一个模型:
<?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');
}
}
我猜当 Laravel 调用 auth() 函数时它正在创建一个无限循环?如何在不使用本地范围的情况下防止这种情况发生?
【问题讨论】: