Laravel multiple midleware for some route

259 Views Asked by At

I am developing web application with laravel 5.2. What i need is i have some off account that distinguished by role. and i have to role that can access 1 route but other role cannot access. i have browsing and i have done everything that i found like

Route::group(['prefix' => '/', 'middleware' => ['role:user_a','role:user_b']], function(){someroute}

Route::group(['prefix' => '/', 'middleware' => ['role:user_a|role:user_b']], function(){someroute}

Route::group(['prefix' => '/', 'middleware' => ['role:user_a,role:user_b']], function(){someroute}

no one work. i dont know how to make my single route can be accessed by 2 role but disable for other role

2

There are 2 best solutions below

2
On

i think you cant do this, but you can use this way.

Route::group(['prefix'=>'/', 'middleware' =>['role:user_a','role:user_b']],function(){

      Route::group(['prefix'=>'userAorB', 'middleware' =>['role:user_a|role:user_b']],function(){ Routes });
      Route::group(['prefix'=>'userAANDB', 'middleware' =>['role:user_a,role:user_b']],function(){ Routes });

})
0
On

You can create a middleware named role, read more about middleware in docs here

The handle method of middleware will be as:

public function handle($request, Closure $next)
{
    if (auth()->user()->role('b')) {
        return redirect('home');
    }
    // else users of other roles can visit the page
    return $next($request);
}

Then you can use it in your route file as:

Route::group(['middleware' => 'role'], function () {
    // someroute
});