0
0
LaravelHow-ToBeginner · 3 min read

How to Use Route Prefix in Laravel for Grouping Routes

In Laravel, you use Route::prefix('prefix-name')->group(function () { ... }); to add a common URL prefix to a group of routes. This helps organize routes that share the same starting path segment easily.
📐

Syntax

The Route::prefix() method takes a string that defines the URL prefix. Inside the group() method, you define all routes that should share this prefix.

Each route inside the group will automatically have the prefix added before its URI.

php
Route::prefix('admin')->group(function () {
    Route::get('dashboard', function () {
        // ...
    });
    Route::get('users', function () {
        // ...
    });
});
💻

Example

This example shows how to group admin routes under the /admin URL prefix. The routes /admin/dashboard and /admin/users will be accessible and handled separately.

php
<?php

use Illuminate\Support\Facades\Route;

Route::prefix('admin')->group(function () {
    Route::get('dashboard', function () {
        return 'Admin Dashboard';
    });

    Route::get('users', function () {
        return 'Admin Users List';
    });
});
Output
Visiting /admin/dashboard shows 'Admin Dashboard'. Visiting /admin/users shows 'Admin Users List'.
⚠️

Common Pitfalls

  • Forgetting to include the group() method after prefix() causes syntax errors.
  • Defining routes outside the group will not have the prefix applied.
  • Using leading slashes in route URIs inside the group can cause unexpected URLs.

Always define route URIs inside the group without a leading slash to correctly append the prefix.

php
/* Wrong way: leading slash breaks prefix */
Route::prefix('admin')->group(function () {
    Route::get('/dashboard', function () {
        return 'Wrong URL';
    });
});

/* Right way: no leading slash */
Route::prefix('admin')->group(function () {
    Route::get('dashboard', function () {
        return 'Correct URL';
    });
});
📊

Quick Reference

Use Route::prefix('prefix')->group(function () { ... }); to add a URL prefix to multiple routes.

Inside the group, define routes without leading slashes.

Combine with middleware or namespace for better route organization.

Key Takeaways

Use Route::prefix('prefix')->group() to add a common URL segment to grouped routes.
Define route URIs inside the group without leading slashes to avoid URL issues.
Always chain group() after prefix() to apply the prefix correctly.
Route prefix helps keep routes organized and URLs consistent.
You can combine prefix with middleware and namespace for better structure.