如何在Laravel 5.2中使用OR条件将多个参数传递给中间件 [英] How to pass multiple parameters to middleware with OR condition in Laravel 5.2

查看:66
本文介绍了如何在Laravel 5.2中使用OR条件将多个参数传递给中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置对两个不同用户角色Admin(普通用户)的访问权限,如下所示.

I am trying to set permission to access an action to two different user roles Admin, Normal_User as shown below.

Route::group(['middleware' => ['role_check:Normal_User','role_check:Admin']], function() {
        Route::get('/user/{user_id}', array('uses' => 'UserController@showUserDashboard', 'as' => 'showUserDashboard'));
    });

管理员或Normal_user均可访问此路由.但是在这种中间件配置中,用户必须同时是Admin和Normal_User.如何在中间件参数传递中添加OR条件?还是有其他授予权限的方法?

This route can be accessed by either Admin or Normal_user. But in this middleware configuration, user is required to be both Admin and Normal_User. How can I add OR condition in middleware parameter passing? Or is there any other method to give permission?

以下是我的中间件

public function handle($request, Closure $next, $role)
    {
        if ($role != Auth::user()->user_role->role ) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return response('Unauthorized.', 401);
            }
        }
        return $next($request);
    }

任何人都可以回复吗?

推荐答案

要添加多个参数,您需要用逗号分隔它们:

To add multiple parameters, you need to seperate them with a comma:

Route::group(['middleware' => ['role_check:Normal_User,Admin']], function() {
        Route::get('/user/{user_id}', array('uses' => 'UserController@showUserDashboard', 'as' => 'showUserDashboard'));
    });

然后您可以像这样在中间件中访问它们:

Then you have access them to in your middleware like so:

public function handle($request, Closure $next, $role1, $role2) {..}

由您决定要执行的逻辑,没有自动的方式说或".

The logic from there is up to you to implement, there is no automatic way to say "OR".

这篇关于如何在Laravel 5.2中使用OR条件将多个参数传递给中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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