How to Use Route Groups and Prefixes in Laravel  11

How to Use Route Groups and Prefixes in Laravel 11

How to group routes and apply prefixes for better organization and consistency in Laravel 11 routes

Introduction

In this article i’ll show you how to use route groups and prefixes in Laravel 11 routes.

The route file in Laravel 11 basically contains pathway through which the application receives internet request to return a response. All routes are defined in the Laravel route directory.

  • For example:

The get method of the Route facade below basically defines the route that returns homepage as a value when the application receives a request via /

The first argument is the URI, followed by a closure in this use case.

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return 'homepage';
});

I’ll dive deep into Laravel routes in my upcoming Laravel series on Hashnode and my Youtube channel. Follow and subscribe to stay informed.

Importance of grouping routes and using prefixes

Depending on the features and functionalities of an application the routes could be many to serve the internet requests with the appropriate responses. This could bring about repetition and difficulty in managing the routes in the route file.

💡
In the video below on my youtube channel i explained how to group use statements in a Laravel route file

Routes Group

Route grouping function in Laravel enables for sharing of similar features such as namespace, controller, middleware, prefixes etc with multiple routes to eliminate repitition. For example you can use prefixes to group routes with common links (URL) parts.

Example of Ungrouped Routes

The example below shows a list of ungrouped routes in a Laravel 11 route file.

We’ll use these snippet to demonstrate various ways to group routes in a Laravel file until it becomes shorter, more readable, easily extendable and cleaner.

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

Route::get('posts/', [PostController::class, 'index'])->middleware('auth')->name('posts.index');
Route::get('posts/create', [PostController::class, 'create'])->middleware('auth')->name('posts.create');
Route::get('posts/show/{ulid}', [PostController::class, 'show'])->middleware('auth')->name('posts.show');
Route::get('posts/edit/{ulid}', [PostController::class, 'edit'])->middleware('auth')->name('posts.edit');
Route::post('posts/store', [PostController::class, 'store'])->middleware('auth')->name('posts.store');
💡
Even though the code snippet above can be simplified using a resource.
    Route::resource('posts', PostController::class);

There are use cases where you would want to have full control of the routing definition.

Group By Prefixes

You can use the Laravel prefix() method to define the prefix for each route in a group. For example: to prefix all route within the grouped route with a posts URL:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

Route::prefix('posts')->group(function () {
    Route::get('/', [PostController::class, 'index'])->name('posts.index');
    Route::get('create', [PostController::class, 'create'])->name('posts.create');
    Route::get('show/{ulid}', [PostController::class, 'show'])->name('posts.show');
    Route::get('edit/{ulid}', [PostController::class, 'edit'])->name('posts.edit');
    Route::post('store', [PostController::class, 'store'])->name('posts.store');
});

All routes inside the group will have the /posts prefix: /posts/, /posts/create, etc and it’s very easy to add more routes that share the same prefix.

💡
Pretty much better??? but there’s more to making it cleaner and shorter. Follow along…

Route Group with Name Prefix

With the route() method in a Laravel blade file you can set the URL for request to be made to a particular route. For example route(‘posts.index‘) is same as url(‘/posts/index‘). The route() method will work even if the URI changes.

The Laravel name() method can be used to prefix each route name in the group with a given string.

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

Route::prefix('posts')->name('posts.')->group(function () {
    Route::get('/', [PostController::class, 'index'])->name('index');
    Route::get('create', [PostController::class, 'create'])->name('create');
    Route::get('show/{ulid}', [PostController::class, 'show'])->name('show');
    Route::get('edit/{ulid}', [PostController::class, 'edit'])->name('edit');
    Route::post('store', [PostController::class, 'store'])->name('store');
});

Much cleaner and shorter with the elimination of duplications posts. in the name method.

Route Group with Middleware

Routes can be grouped to share same middleware. Let’s apply auth middleware to the group route.

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

Route::prefix('posts')
->name('posts.')
->middleware('auth')
->group(function () {
    Route::get('/', [PostController::class, 'index'])->name('index');
    Route::get('create', [PostController::class, 'create'])->name('create');
    Route::get('show/{ulid}', [PostController::class, 'show'])->name('show');
    Route::get('edit/{ulid}', [PostController::class, 'edit'])->name('edit');
    Route::post('store', [PostController::class, 'store'])->name('store');
});

The auth middleware can be applied to the group of routes.

💡
In the video below, i demonstrated How to create and register a middleware in a Laravel 11 application

Route Group with Namespace

With the group method routes can share the same namespace using the Laravel namespace() method. For example in the code below, User is a namespace that is assigned to the grouped controllers.

use Illuminate\Support\Facades\Route;

Route::namespace('User')->group(function () {
    Route::prefix('posts')->name('posts.')->middleware('auth')->group(function () {
        Route::get('/', 'PostController@index')->name('index');
        Route::get('create', 'PostController@create')->name('create');
        Route::get('show/{ulid}', 'PostController@show')->name('show');
        Route::get('edit/{ulid}', 'PostController@edit')->name('edit');
        Route::post('store', 'PostController@store')->name('store');
    });

    Route::get('/dashboard', 'DashboardController@index');
    Route::get('/users', 'UserController@index');
});

The namespace attribute indicates that the Controllers are located in the User folder, so it automatically looks for controllers inside App\Http\Controllers\User.

Route Group with Controller

With the controller() method grouped routes can share the same controller to further eliminate repetition and make the code cleaner.

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

Route::controller(PostController::class)
->prefix('posts')
->name('posts.')
->middleware('auth')
->group(function () {
    Route::get('/', 'index')->name('index');
    Route::get('create', 'create')->name('create');
    Route::get('show/{ulid}', 'show')->name('show');
    Route::get('edit/{ulid}', 'edit')->name('edit');
    Route::post('store', 'store')->name('store');
});

Grouped Routes with Subdomain routing

With the domain() method route groups with same subdomain routing can be accessed.

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

Route::domain('posts.alemsbaja.com')
->controller(PostController::class)
->prefix('posts')
->name('posts.')
->middleware('auth')
->group(function () {
    Route::get('/', 'index')->name('index');
    Route::get('create', 'create')->name('create');
    Route::get('show/{ulid}', 'show')->name('show');
    Route::get('edit/{ulid}', 'edit')->name('edit');
    Route::post('store', 'store')->name('store');
});

Routes inside the group will be accessed via posts.alemsbaja.com/posts/, posts.alemsbaja.com/posts/create etc

Nested Grouped Routes

In Laravel, grouped routes can be grouped. This is essential to make the code much shorter and cleaner in a large application. More common in Laravel API development.

Route::prefix('api')->group(function () {
    Route::prefix('v1')->group(function () {
        Route::middleware('auth')->group(function () {
            Route::prefix('posts')->name('posts.')->controller(PostController::class)->group(function () {
                Route::get('/', 'index')->name('index');
                Route::get('create', 'create')->name('create');
                Route::get('show/{ulid}', 'show')->name('show');
                Route::get('edit/{ulid}', 'edit')->name('edit');
                Route::post('store', 'store')->name('store');
            });

            Route::controller(UserController::class)->group(function () {
                Route::get('/users', 'users');
            });
        });
    });
});

Routes inside the group will have the prefix /api/v1 , /api/v1/posts/, /api/v1/users and will all require authentication for access.

Conclusion

The Route group functionality in Laravel can be utilized for strategic organization and efficiency of routes, especially when handling shared prefixes, middleware, controllers, name etc. It brings enhances simplicity, readability, elimination of duplicates of shared attributes, and ease of modification. More notable is the flexibility to intelligently merge attributes with their parent groups through nesting.

Find this article useful… kindly share with your network and feel free to use the comment section for questions, answers, and contributions.

💡
Follow me on Hashnode: Alemsbaja --- X: Alemsbaja ---- Youtube: Tech with Alemsbaja to stay updated on more articles

Did you find this article valuable?

Support Alemoh Rapheal Baja by becoming a sponsor. Any amount is appreciated!