All the laravel routes are defined in the Route directory. These files are automatically loaded by your application’s App\Providers\RouteServiceProvider.
Route groups allow you to share route attributes, such as middleware, across a large number of routes without needing to define those attributes on each individual route. We can use nested route groups also for the specific middleware, namespace, prefix, etc. Let’s see each one in detail:
1. Middleware
To assign middleware to all routes within a group, you may use the middleware key in the group attribute array.
Route::group(['middleware' => 'auth'], function () { Route::get('/', function () { // Uses Auth Middleware }); });
2. Namespaces
To assign the same PHP namespace to a group of controllers.
Route::group(['namespace' => 'Admin'], function() { Route::group(['namespace' => 'User'], function() { … }); });
3. Route Prefixes
The prefix group array attribute may be used to prefix each route in the group with a given URI.
Route::group(['prefix' => 'admin'], function () { Route::get('users', function () { // Matches The "/admin/users" URL }); });
4. Sub-Domain Routing
Route groups may also be used to route wildcard subdomains. Sub-domains may be assigned route parameters just like route URIs, allowing you to capture a portion of the sub-domain for usage in your route or controller.
Route::group(['domain' => ['admin.example.com']], function() { Route::get('users', function () { … }); });
5. Controllers
If a group of routes all utilize the same controller, you may use the controller method to define the common controller for all of the routes within the group.
use App\Http\Controllers\OrderController; Route::controller(OrderController::class)->group(function () { Route::get('/orders/{id}', 'show'); Route::post('/orders', 'store'); });
6. Route Name Prefixes
The name method may be used to prefix each route name in the group with a given string. The given string is prefixed to the route name exactly as it is specified, so we will be sure to provide the trailing . character in the prefix.
Route::name('admin.')->group(function () { Route::get('/users', function () { // Route assigned name "admin.users"... })->name('users'); });
1. To group multiple domains, we can use pattern and group parameters to achieve this.
Route::pattern('domain', '(web.com|x.web.com)'); Route::group(['domain' => '{domain}'], function () { Route::get('/', function($domain) { // Now all routes receive $domain as the first parameter }); });
2. Another way to achieve this is to just declare the routes in a separate function as pass it to both route groups.
Route::group(['domain' => 'admin.example.com'], function() { ... }); $appRoutes = function() { Route::get('/',function(){ ... }); }; Route::group(['domain' => 'app.example.com'], $appRoutes); Route::group(['domain' => 'dev.app.example.com'], $appRoutes);