Search code examples
phplaravellaravel-4laravel-routinglaravel-filters

laravel - How can i use same url in 2 route group


Suppose I have 2 filters

1) Admin 2) SuperAdmin

Filters:

 Route::filter('Admin', function($route, $request)
 {
   if ( ! Auth::user()->Admin()) {
   return Response::json(array('flash' => 'You are not authorized.'), 401);
 }
});

Route::filter('SuperAdmin', function($route, $request)
{
  if ( ! Auth::user()->SuperAdmin()) {
  return Response::json(array('flash' => 'You are not authorized.'), 401);
}
});

Routes:

Route::group(array('before' => array('auth|Admin')), function()
{

    Route::get('/report/{id}','ReportCntrl@getreport');
    Route::get('/create1','ReportCntrl@create1');

}


Route::group(array('before' => array('auth|SuperAdmin')), function()
{

    Route::get('/report/{id}','ReportCntrl@getreport');
    Route::get('/create2','ReportCntrl@create2');
    Route::get('/create3','ReportCntrl@create3');

}

so the problem is when I login from superadmin it says unauthorized access

because I think it passes my request to both filters and one approves it and second disapproves it.

Is there any way that i can actually use to access same url from 2 route groups in Laravel.


Solution

  • You have to use one single filter. But you can make use of filter parameters to make it dynamic and reusable.

    Route::filter('role', function($route, $request, $value){
        $allowedRoles = explode(';', $value);
        $user = Auth::user();
        if(in_array('Admin', $alloweRoles) && $user->Admin()){
            return;
        }
        else if(in_array('SuperAdmin', $allowedRoles) && $user->SuperAdmin()){
            return;
        }
        return Response::json(array('flash' => 'You are not authorized.'), 401);
    });
    

    And you use it like this:

    Route::group(array('before' => array('auth|role:Admin;SuperAdmin')), function(){
        Route::get('/report/{id}','ReportCntrl@getreport');
    }
    

    Explanation

    The three filter parameters ($route, $request, $value) are automatically passed in that order by Laravel. The third parameter $value contains everything passed after :. Laravel docs

    $request is the current request object (instance of Illuminate\Http\Request) and $route the current route object (instance of lluminate\Routing\Route)