【发布时间】:2019-10-22 13:40:47
【问题描述】:
仅当经过身份验证的用户的角色等于某些东西时,我才需要应用特定的全局范围。这样具有特定角色的用户将只能对给定的记录子集执行查询。
我可以轻松处理 User 模型(当前登录的用户),但不能在范围的 apply 方法内。
https://github.com/laravel/framework/issues/22316#issuecomment-349548374
作用域构造函数执行得非常早,在 auth 中间件之前 已运行。在 apply 方法中解析用户,而不是在构造函数中。
好的,所以我在 apply 方法中:
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class UserScopeForSalesContactAdmin implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
dd('within apply', auth()->user());
dd(auth()->user()); // won't work
$builder->where('foo', '=', 'something from currently logged in user');
}
}
显然第二个dd 给出:
已达到“512”的最大函数嵌套级别,正在中止!
如何解决这个问题?我想我应该通过app()->make() 调用 IOC 容器,但是然后呢?
感谢任何提示。
编辑:我想我知道是什么导致了无限循环 (https://github.com/laravel/framework/issues/26113),但我仍然需要找到获取用户的最佳方法……
【问题讨论】:
-
你试过 Auth::user() 吗?如果您可以将请求放入范围,您也可以尝试 $request->user() 。不知道是什么导致了这种情况,但也许在后台存在冲突,使用解决方法可以解决问题。我不确定,但我认为 Auth::user() 每次使用时都会对数据库进行查询。
标签: php laravel inversion-of-control ioc-container laravel-5.8