Ad

How To Register Middlewares In OctoberCMS Plugin?

Registering middlewares in Laravel is easy:

simply list the middleware class in the $middleware property of your app/Http/Kernel.php class

or

If you would like to assign middleware to specific routes, you should first assign the middleware a short-hand key in your app/Http/Kernel.php file

But how can this be done in an OctoberCMS plugin? Is the "Routing and initialization" meant to be used in place of Kernel.php to register middlewares? If not, where can a plugin register its own middlewares?

Ad

Answer

As mentioned in the Documentation you can extend the controller class inside the the boot method of your plugin.php ;

public function boot()
{

    // Extend Controller Class
    \Cms\Classes\CmsController::extend(function($controller) {
        $controller->middleware('Middleware\Path..');
    });


    // OR Push it directly to the Kernel

      // prependMiddleware : Add a new middleware to beginning of the stack.
     $this->app['Illuminate\Contracts\Http\Kernel']
        ->prependMiddleware('Middleware\Path..');

     // pushMiddleware : Add a new middleware to end of the stack.
     $this->app['Illuminate\Contracts\Http\Kernel']
        ->pushMiddleware('Middleware\Path..');

}

Also you can add it in your plugin's routes.php file :

Route::group(['prefix' => 'foo'], function () {

        Route::get('{slug}', function($slug){

           ....

        })->where('slug', '(.*)?')->middleware('Path\To\Middleware');
});
Ad
source: stackoverflow.com
Ad