Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

EliasSoares's avatar

[L5] Register a route middleware at Package

Lets suppose that my L5 Package have a middleware class.

How do I register a route middleware to use in my package custom routes?

And BTW, does Filter exists in Laravel 5? Whats the advantage using Middleware insted of Filter?

0 likes
7 replies
bobbybouwmann's avatar

There is not yet a way to make some middleware in a package and use that out of the box! The only way is to put it in the Kernel.php file. So you have to tell the user from the package that they need to update the Kernel.php file!

Take a look at this package to give you an idea: https://github.com/kodeine/laravel-acl

EliasSoares's avatar

And how do I use my package middlewares in my package own routes? It's possible to do something like this?

Route::get('package/route', ['middleware' => 'vendor\package\middleware', function()
{
    //
}]);

I've migrated my package, it's working with registered old filters. But is filter a valid approach to use? Or it's deprecated?

bobbybouwmann's avatar

You can still use filters, they are just fine.

I think that if you register your middleware in the Kernel like normal

'auth' => 'App\Http\Middleware\Authenticate',
'myMiddleware' => 'Vendor\Package\Middleware',

And then in your route you can do something like this

Route::get('package/route', ['middleware' => 'myMiddleware', 'uses' => 'MyController@index']); 
cherrypulp's avatar

Just looking for that today and found the answer.

So for the people interested in, the answer is here :

https://github.com/laravel/framework/issues/6211

public function boot(\Illuminate\Routing\Router $router) {
    $router->middleware('name', 'MiddlewareClass');
}
Route::get("yoururl",["middleware" => "name",function(){}]);
4 likes
zelaza's avatar

This is such a beautiful thing.

But to make it work in 5.4 use 'aliasMiddleware()' instead of 'middleware()' thus:

public function boot(\Illuminate\Routing\Router $router) {
    $router->aliasMiddleware('name', 'MiddlewareClass');
}
4 likes
husseinmirzaki's avatar

Just in side the service provider register method write this code :

$this->app['router']->aliasMiddleware('middleware_name' , MyMiddleware::class);
2 likes

Please or to participate in this conversation.