1. Basic Route Group
You can group routes without any additional attributes. For example, you can group routes under a common URL prefix:
In this case, both /home
and /about
routes will work as normal without any changes to their URLs.
2. Applying a URL Prefix
One common use of route groups is to apply a URL prefix to all routes in the group. This is useful when you want to group routes under a common prefix, such as /admin
or /user
.
This will result in the following routes:
-
/admin/dashboard
-
/admin/settings
3. Applying Middleware to a Route Group
You can apply middleware to a group of routes, meaning all the routes in the group will use the same middleware. For example, applying the auth
middleware to ensure the user is authenticated before accessing the routes:
Here, both /profile
and /settings
routes will require the user to be authenticated before they can access the pages.
4. Applying a Namespace to a Group
If you want to group routes under a common namespace for controllers, you can use the namespace
attribute. This is useful for organizing controllers into different folders, such as Admin
or User
controllers.
In this case, Laravel will look for the DashboardController
and SettingsController
in the App\Http\Controllers\Admin
namespace.
5. Applying Multiple Attributes to a Group
You can combine multiple attributes in a route group. For example, you can apply both a prefix, middleware, and namespace at the same time.
This group will:
-
Prefix the routes with
/admin
-
Require the user to be authenticated using the
auth
middleware -
Use the
App\Http\Controllers\Admin
namespace for the controllers
This will result in the following routes:
-
/admin/dashboard
(withauth
middleware) -
/admin/settings
(withauth
middleware)
6. Named Routes with Groups
You can also define named routes within a group. Named routes are useful for generating URLs or redirects in your application.
Now you can generate URLs for these routes using the route name:
7. Resource Routes in a Group
You can also define resource routes within a group, which is particularly useful for CRUD operations.
This will create the following routes for the PostController
:
-
/admin/posts
(GET) → index -
/admin/posts/create
(GET) → create -
/admin/posts
(POST) → store -
/admin/posts/{post}
(GET) → show -
/admin/posts/{post}/edit
(GET) → edit -
/admin/posts/{post}
(PUT/PATCH) → update -
/admin/posts/{post}
(DELETE) → destroy
Conclusion
Route groups in Laravel are a powerful feature to organize and manage your routes more effectively. By grouping routes, you can apply common attributes like prefixes, middleware, and namespaces, which helps keep your code clean and maintainable.