如何在路线Laravel 5中使用'OR'中间件 [英] How to use 'OR' middleware for route laravel 5

查看:81
本文介绍了如何在路线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版中间件可以获取参数-请在此处查看更多详细信息:

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'中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆