Laravel Route::group for Admins

11,816

You can create middleware which will check if user is an admin:

class IsAdmin
{
    public function handle($request, Closure $next)
    {
        if (Auth::user()->permission == 'admin') {
            return $next($request);
        }

        return redirect()->route('some.route'); // If user is not an admin.
    }
}

Register it in Kernel.php:

protected $routeMiddleware = [
    ....
    'is.admin' => \App\Http\Middleware\IsAdmin::class,
];

And then apply it to a route group:

Route::group(['middleware' => 'is.admin'], function () {
    Route::get('/user/{data}', 'UserController@getData');
    Route::post('/user/{data}', 'UserController@postData');
});
Share:
11,816
 Okay
Author by

Okay

Updated on June 04, 2022

Comments

  •  Okay
    Okay almost 2 years

    I would like to authentificate some routes, if the user is admin.

    Route::get( '/user/{data}', 'UserController@getData' );
    Route::post( '/user/{data}', 'UserController@postData' );
    

    Now, I made it inside the Controller:

    public function getData( $data = 'one' )
    {
        if ( Auth::user()->permission == 'admin' ) {
            //...
        } else {
            //...
        }
    }
    
    public function postData( Request $request, $data = 'one' )
    {
        if ( Auth::user()->permission == 'admin' ) {
            //...
        } else {
            //...
        }
    }
    

    I would like to make it with Route::group, but how can I do that in the routes.php?

  • andcl
    andcl about 5 years
    Yes, the prebuilt authorization mechanism in Laravel lets you do that even smarterly through Gates... See laravel.com/docs/5.8/authorization