Laravel: Route Group Attributes

Laravel provides a nice and convenient API for us to define our app routes. There are 2 ways to define a route group: the array syntax via group() or the method syntax. Personally I love the array syntax by calling the group() method provided by the Route facade. However using it is not as straightforward as one may think, and primary reason for that is because it is undocumented at the time of writing this article.

So What is a Route Group?

Route group essentially helps us to group multiple routes together under the same middleware, prefix, name or namespace. This is especially convenient when we have a group of similar routes e.g. routes that are related to the same resource.

For example, suppose we want to group our user routes together. Let’s take a look at the code and compare both ways of defining the group.

And below is the result from php artisan route:list :

The results from php artisan route:list


If we want to define route name prefix in the array syntax, we need to use the as key (not the name key as opposed to the method syntax).

Key attributes

  1. Prefix — this will add a prefix to all the routes in the group. In the example above, we added a prefix heyaa to all of the user routes:
  2. As/Name — this will add a prefix to the route names. In the example above, we added the users. route name prefix to all routes.
  3. Namespace — this will help the router to resolve the controller. This is required if you want to invoke controller methods using the string syntax, i.e. <controller_class>@<method_name> .
  4. middleware — this will add the specified middleware to all of the routes in the group. You can either pass middleware group name, middleware alias or the full middleware class name.

That’s it!

Web Development. . Follow me on Youtube: