对于这个中间件,您只需要检查查看站点所需的division 是否与用户所属的division 相同。在handle 函数中,可以传递第三个参数,代表一个部门名称,例如customer
当您将中间件添加到您的路由时,您可以将部门名称作为参数传递给 handle 函数,如下所示:
'middleware' => ['division:customer']
在Route Group 中实现它可能看起来像这样:
Route::group(['prefix' => 'customer', 'middleware' => ['division:customer']], funtion(){
//route definitions for all these routes will require a "division" type of "customer"
});
或者您可以将其应用于RESTful 路由的路由资源:
Route::resource('customer', 'CustomerController')->middleware(['divison:customer']);
或者您可以将其应用于特定路线:
Route::get('customer/{id}', 'CustomerController@show')->middleware(['division:customer']);
在您的 handle 函数中,您可以将该值作为第三个参数访问:
public function handle($request, Closure $next, Division $division)
为了使通过主键以外的其他方式自动解决依赖关系的过程变得容易,我们将继续打开 App\Providers\RouteServiceProvider 并在 boot 函数中添加一些魔法。
public function boot(Router $router)
{
parent::boot($router);
$router->bind('division', function($value) {
return Division::where(function($query) use($value){
if (is_int($value)) {
return $query->where('id', $value)->first();
} else {
return $query->where('type', ucfirst($value))->first();
}
return null;
});
});
现在,回到中间件,我们可以轻松地与 handle 函数中的 $division 和 authorized 用户进行比较。
if(app()->user()->division->type == $division->type) {
return $next($request);
}
abort(403, 'You are not authorized to view this page!');