Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass multiple parameters to middleware with OR condition in Laravel 5.2

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'));
    });

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?

The following is my middleware

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);
    }

Can anyone please reply?

like image 428
manoos Avatar asked Aug 02 '16 05:08

manoos


People also ask

How do you pass arguments to middleware?

To achieve this, you can use a simple but efficient pattern: wrap your actual middleware function with a second one that receives the desired parameters, like so. Then, simply pass the desired parameter to the middleware wrapper function when passing to the Express routes. Of course this works with 1..n parameters.

How do you call multiple middleware in Laravel?

You can assign multiple middlewares to Laravel route by using middleware method. Route::group(['middleware' => ['firstMiddleware','secondMiddleware']], function () { // }); This post is submitted by one of our members.

How do I add multiple Middlewares?

To assign middleware to a route you can use either single middleware (first code snippet) or middleware groups (second code snippet). With middleware groups you are assigning multiple middleware to a route at once. You can find more details about middleware groups in the docs.

Can we use multiple middleware?

We can use more than one middleware on an Express app instance, which means that we can use more than one middleware inside app. use() or app. METHOD() .


Video Answer


1 Answers

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".

like image 143
Chris Avatar answered Oct 04 '22 23:10

Chris