Laravel add custom middleware to route group

DolDurma picture DolDurma · May 19, 2018 · Viewed 20.6k times · Source

in my web application i have admin panel and i'm trying to make access to users that they have admin role by this code:

namespace App\Http\Middleware;
use Closure;
class CheckUserAdminRole
{
    public function handle($request, Closure $next)
    {
        if (auth()->check()) {
            if (auth()->check() && !auth()->user()->hasRole('admin')) {
                auth()->logout();
                return redirect(route('system.messages','userIsNotAdmin'));
            }
        }
        return $next($request);
    }
}

and in my routs i have this route group:

Route::group(['namespace' => 'Dashboard', 'middleware' => ['auth:web'], 'prefix' => 'dashboard'], function () {
    $this->group(['prefix' => 'administrator'], function () {
        $this->get('panel', 'AdminController@index');
});

my kernel:

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    ...
    \App\Http\Middleware\CheckUserAdminRole::class,
];

now when i add my middleware as CheckUserAdminRole to route group like with this code:

Route::group(['namespace' => 'Dashboard', 'middleware' => ['auth:web','CheckUserAdminRole'], 'prefix' => 'dashboard'], function () {

i get this error:

Class CheckUserAdminRole does not exist

this codes couldn't resolve my problem:

php artisan route:clear
php artisan cache:clear
php artisan config:clear
composer dump-autoload

Answer

SystemGlitch picture SystemGlitch · May 19, 2018

Instead of registering your middleware in the $middleware array, you should register it in $routeMiddleware like so:

protected $routeMiddleware = [
    ...
    'checkAdmin' => \App\Http\Middleware\CheckUserAdminRole::class,
];

Note: registering a middlware in the $middleware array results in it being executed for every request and therefore is not applicable on specific routes.

Then you can use it in your routes with the checkAdmin name:

Route::group(['namespace' => 'Dashboard', 'middleware' => ['auth:web','checkAdmin'], 'prefix' => 'dashboard'], function () {

Source