0
votes

The delivered auth middleware that comes with Laravel 5 is great for user-only routes and controllers, however I want to add the ability to also check if the user is an administrator.

Currently, in my controllers, I have this for every class:

if (Auth::user()->level <= 1) {
    // admin can do these actions
} else {
    // redirect
}

It's very redundant and I'd like to look at what my options are. Since I want to retain the original auth middleware for user authentication, should I be building a new one for administrator authentication, or can I make some simple change in the original auth middleware that can account for my code above?

1

1 Answers

4
votes

Middleware in Laravel 5.0 do not support arguments (this will be added in the upcoming 5.1 release).

Your options are to either create a separate middleware for this, or use route filters.


You can create a route filter by putting this in your RouteServiceProvider's boot method:

$router->filter('userLevel', function($route, $request, $level)
{
    $user = auth()->user();

    if ( ! $user || $user->level > $level)
    {
        return response('Unauthorized', 401);
    }
});

Then use that filter in your routes:

Route::group(['before' => 'userLevel:1'], function($router)
{
    // define routes...
});