Middleware

Concepts

You can use a middleware to filter routes and route groups by permission, role or ability:

Route::group(['prefix' => 'admin', 'middleware' => ['role:admin']], function() {
    Route::get('/', 'AdminController@welcome');
    Route::get('/manage', ['middleware' => ['permission:manage-admins'], 'uses' => 'AdminController@manageAdmins']);
});

If you use the pipe symbol it will be an OR operation:

'middleware' => ['role:admin|root']
// $user->hasRole(['admin', 'root']);

'middleware' => ['permission:edit-post|edit-user']
// $user->hasRole(['edit-post', 'edit-user']);

To emulate AND functionality you can do:

'middleware' => ['role:owner|writer,require_all']
// $user->hasRole(['owner', 'writer'], true);

'middleware' => ['permission:edit-post|edit-user,require_all']
// $user->hasRole(['edit-post', 'edit-user'], true);

For more complex situations use ability middleware which accepts 3 parameters: roles, permissions, validate_all:

'middleware' => ['ability:admin|owner,create-post|edit-user,require_all']
// $user->ability(['admin', 'owner'], ['create-post', 'edit-user'], true)

Teams

If you are using the teams feature and want to use the middleware checking for your teams, you can use:

'middleware' => ['role:admin|root,my-awesome-team,require_all']
// $user->hasRole(['admin', 'root'], 'my-awesome-team', true);

'middleware' => ['permission:edit-post|edit-user,my-awesome-team,require_all']
// $user->hasRole(['edit-post', 'edit-user'], 'my-awesome-team', true);

'middleware' => ['ability:admin|owner,create-post|edit-user,my-awesome-team,require_all']
// $user->ability(['admin', 'owner'], ['create-post', 'edit-user'], 'my-awesome-team', true);

Note

The require_all is optional.

Middleware Return

The middleware supports two types of returns in case the check fails. You can configure the return type and the value in the config/laratrust.php file.

Abort

By default the middleware aborts with a code 403 but you can customize it by changing the middleware_params value.

Redirect

To make a redirection in case the middleware check fails, you will need to change the middleware_handling value to redirect and the middleware_params to the route you need to be redirected. Leaving the configuration like this:

'middleware_handling' => 'redirect',
'middleware_params'   => '/home',       // Change this to the route you need