Router Controller Grouping Laravel

Laravel Router Controller Grouping

Routing

Laravel routes accept a URI and a closure, providing a very simple and expressive method of defining the routes and the behavior without complicated routing configuration files.

use Illuminate\Support\Facades\Route;
 
Route::get('/welcome', function () {
    return 'Hello World';
});

Router Grouping

The route groups allow you to share the route attributes, such as the middlewares, across a large number of routes without needing to define those attributes with each individual route.

Nested groups attempt to intelligently “merge” attributes with their parent group. Middleware andĀ where conditions are merged while the names and prefixes are appended. Namespace delimiters and slashes in the URI prefixes are automatically added where appropriate.

Laravel router controller grouping

The router controller grouping method is used to define the common controller for all of the routes within the group.
Now instead of writing the controller class with every route, we can define the group for them, and then we can simply pass the routes with their methods. Below is the example for using the grouping with before and after using the controller-based routers grouping.

Normal Router without grouping:

Route::get('/posts/{id}', [PostController::class, 'show']);
Route::post('posts', [PostController::class, 'store']);

After using the Controller grouping:

use App\Http\Controllers\PostController;
 
Route::controller(PostController::class)->group(function () {
    Route::get('/posts/{id}', 'show');
    Route::post('/posts', 'store');
});

You can clearly see the differences here. the code goes shorter, more oriented, and easy to read. Not only the controller but there are few other grouping methods are available, which will help you to make your code more robust and easy to handle. You can check those other ways using the links below from the official Laravel website. Although, this particular grouping is available for Laravel 9. Although, the other method are working with other Laravel versions too. Some grouping methods are :

  • Middleware Routing
  • Subdomain Routing
  • Route Prefixes
  • Route Name Prefixes

You can get more details about this topic fromĀ here.

To get to know more about the Laravel, you can check these articles too

Please follow and like us:

Related Posts

Leave a Reply

Share