无法在Laravel 5.2的Scope类内调用Auth类 [英] Can not call Auth class inside Scope class in Laravel 5.2
问题描述
我添加了用户模型的外部范围.简单创建的Scope,名称为DeveloperScope
I added External Scope for User Model. Simply created Scope, with the name DeveloperScope
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Auth;
class DeveloperScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
if(Auth::user()->id != 1){
$builder->where('id', '<>', 1);
}
}
}
然后,我将此范围称为用户模型.
Then, I called this scope for User model.
用户模型
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\Scopes\DeveloperScope;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use SoftDeletes;
use Authenticatable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['first_name', 'last_name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
protected $dates = ['deleted_at'];
protected static function boot()
{
parent::boot();
static::addGlobalScope(new DeveloperScope);
}
}
当我在DeveloperScope
类中不使用Auth::class
时,效果很好.原因是,我只想为所有Eloquent方法的其他用户隐藏主要用户.当然,我可以使用会话代替Auth并检索用户ID.但是对我来说仍然很有趣,为什么浏览器在使用Auth::class
时会出现错误:ERR_EMPTY_RESPONSE
?
It works well, when I don't use Auth::class
inside DeveloperScope
class. The reason is that, I just want to hide the main user for another users for all Eloquent methods. Of course, I can use session instead of Auth and retrieve user id. But it is still interesting for me, why browser gives an error: ERR_EMPTY_RESPONSE
while using Auth::class
?
推荐答案
您要查找的方法正是 Auth::hasUser()
.该方法是通过我的PR在Laravel 5.6中添加的. (因此,您需要先升级Laravel)
The method what you are looking for is exactly Auth::hasUser()
. The method was added in Laravel 5.6 through my PR. (So you need to upgrade Laravel first)
[5.6]增加了确定当前用户是否已通过身份验证而不会触发副作用的功能mpyw·拉取请求#24518·laravel/框架
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
class DeveloperScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
if (!Auth::hasUser() || Auth::user()->id != 1) {
$builder->where('id', '<>', 1);
}
}
}
只需调用Auth::hasUser()
即可防止Auth::user()
引起副作用.
Just call Auth::hasUser()
to prevent Auth::user()
from causing side effects.
这篇关于无法在Laravel 5.2的Scope类内调用Auth类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!