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?
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.
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.
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.
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() .
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With