Naming Routes in Laravel: A Practical Guide

Updated: January 18, 2024 By: Guest Contributor Post a comment

Introduction

Routes are the cornerstone of any Laravel application. They direct incoming requests to various parts of your application, often resulting in a response being sent back to the user. To simplify the management of these routes, Laravel allows you to assign names to them. This guide will walk you through naming routes in Laravel, showing you why it’s beneficial and how you can leverage this feature to write cleaner code.

Imagine a complex application with hundreds of routes. Scanning URLs throughout your code might not only get tiresome but also lead to broken links if you ever have to change your URI schemes. With named routes, you can forget about hardcoding URIs in your views and controllers. Let’s dive into the practical aspect of implementing this feature.

Setting Up Your Laravel Application

Before you can start naming routes, you must have a Laravel environment set up. You could ensure that you have Composer installed and run the following command to create a new Laravel project:

composer create-project --prefer-dist laravel/laravel myAppName

Naming Routes

After setting up your Laravel project, you can name routes by chaining the name method onto your route definitions in the routes/web.php file. Here’s a simple get route with a name:

Route::get('user/profile', function () {
    return 'This is the profile page!';
})->name('profile');

Now, whenever you want to refer to this route in your application, you only need to reference its name, ‘profile’.

Generating URLs To Named Routes

Generating URLs in your application couldn’t be more straightforward. The route function helps generate a URL to a named route.

$url = route('profile');

In your blade templates, it’s just as simple:

<a href="{{ route('profile') }}">View Profile</a>

Passing Parameters To Named Routes

Named routes can also handle parameters. Let’s name a route with a required parameter:

Route::get('user/{id}/profile', function ($id) {
    return "This is the profile page for user {$id}";
})->name('profile.with.id');

You can pass the parameters as the second argument in an associative array when calling the route function.

$url = route('profile.with.id', ['id' => 1]);

In a blade template:

<a href="{{ route('profile.with.id', ['id' => 1]) }}">View Profile</a>

Grouping Named Routes

To keep your route file tidy, you might want to group routes. You can also group named routes which comes in handy, especially for prefixing.

Route::prefix('admin')->name('admin.')->group(function () {
    Route::get('dashboard', function () {
        // Route assigned name "admin.dashboard"
    })->name('dashboard');

    Route::get('users', function () {
        // Route assigned name "admin.users"
    })->name('users');
});

Middleware and Named Routes

Sometimes, you want to assign middleware to your routes:

Route::middleware(['auth'])->group(function () {
    Route::get('profile', function () {
        // Uses Auth Middleware
    })->name('profile');
});

Checking The Current Route Name

The currentRouteName method returns the name of the route handling the current request:

if (Route::currentRouteName() == 'profile') {
    // Execute something specific for the profile route
}

Renaming Routes in Resource Controllers

When you generate a resource controller, Laravel automatically creates named routes for each action in the controller. However, you can customize those names:

Route::resource('photos', 'PhotoController')->names([
    'create' => 'photos.build'
]);

Testing Named Routes

Finally, named routes can make your tests more readable. Rather than typing the actual URL, you reference the route’s name:

public function testProfilePage()
{
    $response = $this->get(route('profile'));

    $response->assertStatus(200);
}

Final Words

This Laravel route naming guide has shown you the flexibility of working with names rather than URLs. Named routes will result in cleaner code, reduced errors from typos or changes in route’s URLs, and smoother testing experience. The next time you’re working with routes in Laravel, consider naming them—it’s a small change with outsized benefits.