Custom route overrides in Laravel modules

I’m currently working on an application which uses the laravel-modules package by nwidart. I have used this package on multiple occasions before, but this time I had to do something new. The modules had to accept custom route overrides.

The traditional approach

Normally, when you have to override package routes, you need to add the package routes provider above the application route provider in config/app.php. This does not work when working with modules since each module loads the route provider through its main provider. So instead we have to use the group method in the module route provider.

The solution

Open up Modules/<module>/Providers/RouteServiceProvider.php. Here we see methods like mapWebRoutes() and mapApiRoutes(). To add support for custom route overrides, all we need to do is a minor tweak of these methods.

The part that matters here is what happens inside  ->group(function() {}). This will first include the default module routes…

… then it will look for overrides in the default Laravel routes location.

Replace <module>  with whatever you want. I personally prefer to use a lowercase version of the module name.

Now we can add a folder inside ./routes/<module>/web.php  and these routes will override any default module routes.

If you find my posts helpful, feel free to buy me a coffee, and if you have any suggestions or questions, feel free to leave me a comment below or send me a message on Twitter