Laravel register Middleware in Package ServiceProvider

How to alias Laravel middleware from service provider

Panjeh
2 min readFeb 8, 2021

By default Laravel register a middleware using kernel.php file inside Http directory.

As you see each middleware has an alias.

Later, I will tell you how to make your project modular. Stay tuned!

And if you want to create a new middleware, you should create it inside Http/Middleware directory and then register it in kernel.php as you see above.

The question is if we make our project modular and every file and directory of the project are inside a custom domain directory, how we should register the middleware?

Or if we are making a package and it has its service provider how we can register the middleware inside the service provider.

The solution is to put this line inside the register() method of our package serviceprovider. and fill it properly with the correct key and value.

app('router')->aliasMiddleware(key, value);

As an example we put for then key the alias and for the value the full string of the class name.

app('router')->aliasMiddleware('my-package-middleware-alias', \My-Package\Middleware::class);

I would like to introduce two packages for Laravel that I have recently developed: Laravel Pay Pocket, a modern multi-wallet package, and Laravel Failed Jobs, a UI for the Laravel Failed Jobs Table. I hope they may be of help to you.

https://github.com/HPWebdeveloper/laravel-pay-pocket
https://github.com/HPWebdeveloper/laravel-failed-jobs

--

--

Panjeh
Panjeh

Written by Panjeh

Posting about Python and Laravel

No responses yet