##Default Middleware
For checking against a single permission (see Best Practices) using can
, you can use the built-in Laravel middleware provided by \Illuminate\Auth\Middleware\Authorize::class
like this:
Route::group(['middleware' => ['can:publish articles']], function () {
});
##Package Middleware
This package comes with RoleMiddleware
, PermissionMiddleware
and RoleOrPermissionMiddleware
middleware. You can add them inside your app/Http/Kernel.php
file.
Note the differences between Laravel 10 and older versions of Laravel is the name of the protected
property:
##Laravel 9 (and older)
protected $routeMiddleware = [
'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
'role_or_permission' => \Spatie\Permission\Middlewares\RoleOrPermissionMiddleware::class,
];
##Laravel 10
protected $middlewareAliases = [
'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
'role_or_permission' => \Spatie\Permission\Middlewares\RoleOrPermissionMiddleware::class,
];
See a typo? You are reading older v5
documentation. Note that since v6 the 'Middleware' namespace is singular. Prior to v6 it was 'Middlewares'. If you are still using 'Middlewares' (plural), it is time to upgrade your app to the latest version of this package!
YOU SHOULD ALSO set the $middlewarePriority
array to include this package's middleware before the SubstituteBindings
middleware, else you may get 404 Not Found responses when a 403 Not Authorized response might be expected.
##Middleware via Routes
Then you can protect your routes using middleware rules:
Route::group(['middleware' => ['role:super-admin']], function () {
});
Route::group(['middleware' => ['permission:publish articles']], function () {
});
Route::group(['middleware' => ['role:super-admin','permission:publish articles']], function () {
});
Route::group(['middleware' => ['role_or_permission:publish articles']], function () {
});
You can specify multiple roles or permissions with a |
(pipe) character, which is treated as OR
:
Route::group(['middleware' => ['role:super-admin|writer']], function () {
});
Route::group(['middleware' => ['permission:publish articles|edit articles']], function () {
});
Route::group(['middleware' => ['role_or_permission:super-admin|edit articles']], function () {
});
##Middleware with Controllers
You can protect your controllers similarly, by setting desired middleware in the constructor:
public function __construct()
{
$this->middleware(['role:super-admin','permission:publish articles|edit articles']);
}
public function __construct()
{
$this->middleware(['role_or_permission:super-admin|edit articles']);
}
(You can use Laravel's Model Policy feature with your controller methods. See the Model Policies section of these docs.)