隐式绑定路由中间件的问题
我的路由
# 这里不限制 status
Route::resource('user.exposures', UserExposuresController::class)->scoped();
# 这里限定 status 为 1
Route::resource('exposures', ExposuresController::class)
->middleware([ScopeStatus::class])
->only(['index', 'show']);
ScopeStatus
中间件
public function handle(Request $request, Closure $next)
{
app()->bind('scope.status', function () {
return true;
});
return $next($request);
}
Exposure
模型
public static function booted()
{
if (app('scope.status')) {
static::addGlobalScope(new StatusScope);
}
}
问题
index
没有问题, 但是 show
方法,是先获得了模型后执行的中间件,也就是 booted
中获得的 app('scope.status')
为 false
,这样我就没办法排除 status
为 0
的模型
我试过直接在中间件加全局查询范围,结果也是一样的
public function handle(Request $request, Closure $next) { Exposure::addGlobalScope('status', function (Builder $builder) { $builder->where('status', 1); }); return $next($request); }
大家有什么优雅的解决办法
我这种情况一般不走中间件限制,用「用户授权」里面的策略解决,个人浅见