Modularize Routes using functions #Laravel - ADVANTAGES!

Video thumbnail

I want to talk a little bit about how you can modularize your routes, since one of the "problems," so to speak, we can have in Laravel is the routes themselves.

Usually, they're all defined at the same level, or the grouping part isn't part of a clear organization as such, but rather responds to a specific need, depending on how you want to present a module.

For example:

  • If a module is protected, then you add certain routes.
  • If it starts with a certain pattern, you add other routes.
  • If you want to run middleware, you add another set of routes.

But again: this is not part of real modularization.

What do I mean by modularize?

I'm referring to placing routes directly in separate modules. For example, in my academic application (the academic website you're looking at here), I manage some routes, although practically nothing, because it's a Vue application, so everything is handled by Vue.

I have the blog and the management part, which would be like three modules. So, that's where I say, "We could group the routes."

Ways to modularize routes
We have a couple of ways to modularize:

1 Within the same file

This is the simplest way and the one that would work for the vast majority. You simply define functions within the routes file. This is sometimes overlooked, but remember, we're in PHP, so you can use anything PHP has to offer: functions, classes, etc.

Although using classes for this seems a bit more complicated to me, it already works quite well with functions.

So what do I do? I define functions like routesDashboard(), group them there; routesBlog(), group them there too, and then define where they'll be used, for example in an if condition.

if (condición) {
   rutasDashboard();
}

Or through subdomains:

if (app()->environment('production')) {
   // Uso el subdominio
   Route::domain('dashboard.miapp.com')->group(function () {
       rutasDashboard();
   });
} else {
   // Uso un prefijo en el path
   Route::prefix('dashboard')->group(function () {
       rutasDashboard();
   });
}

2. Separate files

You can also create separate files, for example:

  • routes_dashboard.php
  • routes_academy.php
  • routes_blog.php

There you define your routes and then import them into your main file.

This option is useful if you have a lot of routes and it becomes difficult to read or maintain everything in a single file.

Conclusion

So, to recap:

  • You can modularize routes using functions within the same file.
  • If you have many, you can use separate files.
  • You can use conditions to distinguish between production and local.
  • And you can avoid duplication and clutter by grouping routes neatly.

I agree to receive announcements of interest about this Blog.

I'll show you the advantages of using functions to define your routes, which is very useful when you want to organize them, define subdomains, etc.

- Andrés Cruz

En español