Laravel add custom middleware to route group

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


You can also use middleware and route group together easily like so:

Route::group(['prefix' => 'admin',  'middleware' => 'auth'], function()
{
    //All the routes that belongs to the group goes here
    Route::get('dashboard', function() {} );
});

Here's a simple fix without touching the Kernel file and taking advantage of the Policy. The accessAdmin is a function created inside Policy file.

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