Skip to content

Route Groups

Joshua Parker edited this page Sep 2, 2020 · 3 revisions

It is common to group similar routes behind a common prefix. This can be achieved using Route Groups:

$router->group(['prefix' => 'page'], function ($group) {
    $group->map(['GET'], '/route1/', function () {}); // `/page/route1/`
    $group->map(['GET'], '/route2/', function () {}); // `/page/route2/`
});

Namespaces

Another common use-case for route groups is assigning the same PHP namespace to a group of controllers using the namespace parameter in the group array:

$router->group(['namespace' => '\Mvc\App\MyControllers'], function ($group) {
    // Controllers Within The "\Mvc\App\MyControllers" Namespace
});

Domain/Subdomain Routing

Route groups may also be used to handle domain/subdomain routing. The domain may be specified using the domain key on the group attribute array while the subdomain may be specified using the subdomain key:

$router->group(['domain' => 'example.com'], function ($group) {
    $group->get('/user/{id}/', function ($id) {
        //
    });
});

$router->group(['subdomain' => 'api.example.com'], function ($group) {
    $group->get('/v1/get/', function () {
        //
    });
});

Route Prefixes

The prefix group attribute may be used to prefix each route in the group with a given url. For example, you may want to prefix all route urls within the group with admin:

$router->group(['prefix' => 'admin'], function ($group) {
    $group->get('/users/', function () {
        // Matches The "/admin/users/" URL
    });
});
Clone this wiki locally