0
0
Laravelframework~5 mins

Route prefixes in Laravel

Choose your learning style9 modes available
Introduction

Route prefixes help group similar routes under a common URL part. This keeps your URLs organized and easier to manage.

You want all admin pages to start with /admin in the URL.
You have an API with many endpoints starting with /api.
You want to group user-related routes under /user.
You want to add a common prefix to routes for versioning like /v1.
You want to apply middleware or settings to a group of routes sharing a prefix.
Syntax
Laravel
Route::group(['prefix' => 'prefix'], function () {
    // Define routes here
});
The prefix string is added before all routes inside the group.
You can nest prefix groups for more complex URL structures.
Examples
This groups routes under the /admin prefix. The full URL for the dashboard is /admin/dashboard.
Laravel
Route::group(['prefix' => 'admin'], function () {
    Route::get('/dashboard', function () {
        return 'Admin Dashboard';
    });
});
This creates an API route at /api/users.
Laravel
Route::group(['prefix' => 'api'], function () {
    Route::get('/users', function () {
        return 'User list';
    });
});
Multiple routes share the /user prefix, so URLs are /user/profile and /user/settings.
Laravel
Route::group(['prefix' => 'user'], function () {
    Route::get('/profile', function () {
        return 'User Profile';
    });

    Route::get('/settings', function () {
        return 'User Settings';
    });
});
Sample Program

This example groups blog-related routes under the /blog prefix. So the URLs are /blog/posts and /blog/posts/{id}.

Laravel
<?php

use Illuminate\Support\Facades\Route;

Route::group(['prefix' => 'blog'], function () {
    Route::get('/posts', function () {
        return 'List of blog posts';
    });

    Route::get('/posts/{id}', function ($id) {
        return "Viewing post with ID: $id";
    });
});
OutputSuccess
Important Notes

Route prefixes do not change the route names unless you also use name prefixes.

You can combine prefix with middleware or namespace for better route organization.

Summary

Route prefixes add a common URL part to grouped routes.

They help keep URLs clean and organized.

Use them to group related routes like admin, API, or user sections.