如何为路由 laravel 5 使用“OR"中间件

时间:2022-11-25
本文介绍了如何为路由 laravel 5 使用“OR"中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种类型的用户,我已经创建了多个中间件.

I've two types for user and I've created multiple middlewares.

有些路由需要允许两种类型的用户.

Some routes need to allow for both type of user.

我正在尝试以下代码:

Route::group(['namespace' => 'Common', 'middleware' => ['Auth1', 'Auth2']], function() {
    Route::get('viewdetail', array('as' => 'viewdetail', 'uses' => 'DashboardController@viewdetail'));
}); 

但它不起作用:(

推荐答案

中间件应该返回响应或将请求传递到管道中.中间件彼此独立,不应该知道其他中间件在运行.

Middleware is supposed to either return a response or pass the request down the pipeline. Middlewares are independent of each other and shouldn't be aware of other middlewares run.

您需要实现一个单独的中间件,允许 2 个角色或单个中间件,将允许的角色作为参数.

You'll need to implement a separate middleware that allows 2 roles or single middleware that takes allowed roles as parameters.

选项 1:只创建一个中间件是 Auth1 和 Auth2 的组合版本,用于检查 2 种用户类型.这是最简单的选择,虽然不是很灵活.

Option 1: just create a middleware is a combined version of Auth1 and Auth2 that checks for 2 user types. This is the simplest option, although not really flexible.

选项 2:由于 5.1 版 中间件可以接受参数 - 请在此处查看更多详细信息:https://laravel.com/docs/5.1/middleware#middleware-parameters.您可以实现一个单一的中间件,该中间件将接受用户角色列表进行检查,并在您的路由文件中定义允许的角色.以下代码应该可以解决问题:

Option 2: since version 5.1 middlewares can take parameters - see more details here: https://laravel.com/docs/5.1/middleware#middleware-parameters. You could implement a single middleware that would take list of user roles to check against and just define the allowed roles in your routes file. The following code should do the trick:

// define allowed roles in your routes.php
Route::group(['namespace' => 'Common', 'middleware' => 'checkUserRoles:role1,role2', function() {
  //routes that should be allowed for users with role1 OR role2 go here
}); 

// PHP < 5.6
// create a parametrized middleware that takes allowed roles as parameters
public function handle($request, Closure $next) {

  // will contain ['role1', 'role2']
  $allowedRoles = array_slice(func_get_args(), 2);

  // do whatever role check logic you need
}

// PHP >= 5.6
// create a parametrized middleware that takes allowed roles as parameters
public function handle($request, Closure $next, ...$roles) {

  // $roles will contain ['role1', 'role2']

  // do whatever role check logic you need
}

这篇关于如何为路由 laravel 5 使用“OR"中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:Laravel 在单个子句中使用多个 where 和 sum 下一篇:Laravel 5 字符集在视图上无法正常工作.但是当我从

相关文章

最新文章