Table of Contents
Why use Route Groups?
How to define a Route Group?
Common configuration items and usage scenarios
1. Routing prefix (prefix)
2. Middleware (middleware)
3. Namespace
4. Subdomain name routing (domain)
Nested Groups
Tips: Notes on naming routing groups
Home PHP Framework Laravel How to define and use Route Groups in Laravel.

How to define and use Route Groups in Laravel.

Jul 21, 2025 am 02:15 AM
laravel routing group

Route Groups in Laravel are used to unify and manage routing of multiple shared settings to reduce duplicate code and improve readability. Route Groups can centrally handle middleware, namespace, route prefix, subdomain binding and other configurations, such as: 1. Use prefix to set routing prefix, which is often used in API or background paths; 2. Unified middleware application through middleware; 3. Simplify controller calls with namespace; 4. Use domain to implement subdomain name routing; 5. Support nested routing groups to achieve finer granular control; 6. Provide unified prefix for route naming with as parameters to improve maintenance efficiency.

How to define and use Route Groups in Laravel.

In Laravel, Route Groups is a very practical feature that allows you to uniformly configure and manage a set of routes. Through Route Groups, you can centrally handle middleware, namespace, route prefix, subdomain binding and other settings to avoid duplicate code and improve code readability and maintenance.

How to define and use Route Groups in Laravel.

Why use Route Groups?

In actual development, we often encounter situations where multiple routes share the same configuration, such as:

  • Multiple background management pages require auth and admin middleware
  • API routing usually starts with /api
  • The front-end pages use namespaces like App\Http\Controllers\HomeController

If you write configurations on each route, it will not only repeat, but also make mistakes prone. After using Route Groups, these configurations can be set uniformly and written only once.

How to define and use Route Groups in Laravel.

How to define a Route Group?

Laravel's routing group is defined using Route::group() method, passing an array as configuration item, and then a closure to define all routes within the group.

 Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function () {
    Route::get('dashboard', [AdminController::class, 'dashboard']);
    Route::get('users', [AdminController::class, 'users']);
});

The above code defines a routing group, and all routes in the group will be automatically prefixed with the /admin prefix and auth middleware is applied.

How to define and use Route Groups in Laravel.

Common configuration items and usage scenarios

1. Routing prefix (prefix)

Applicable to API or background management pages. For example:

 Route::group(['prefix' => 'api/v1'], function () {
    Route::get('users', [UserController::class, 'index']);
});

The access path is: /api/v1/users

2. Middleware (middleware)

Middleware can be set uniformly for a set of routes:

 Route::group(['middleware' => ['auth', 'admin']]], function () {
    Route::get('admin/dashboard', [AdminController::class, 'dashboard']);
});

3. Namespace

If your controller is distributed in different directories, you can use the namespace:

 Route::group(['namespace' => 'Admin', 'prefix' => 'admin'], function () {
    Route::get('settings', [SettingsController::class, 'index']);
});

This way you can write SettingsController::class directly without writing the complete namespace.

4. Subdomain name routing (domain)

Suitable for multi-tenant or subsites:

 Route::group(['domain' => '{account}.example.com'], function () {
    Route::get('users', [UserController::class, 'index']);
});

Nested Groups

You can also nest a routing group in the routing group to achieve finer granular control:

 Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function () {
    Route::group(['namespace' => 'Settings'], function () {
        Route::get('profile', [ProfileController::class, 'index']);
        Route::get('email', [EmailController::class, 'index']);
    });
});

In this way, /admin/profile and /admin/email will inherit prefix and middleware , and the controller uses Settings subnamespace.


Tips: Notes on naming routing groups

If you want to name the routes in the group, it is recommended to use as parameter to prefix the route group:

 Route::group(['prefix' => 'admin', 'as' => 'admin.'], function () {
    Route::get('dashboard', [AdminController::class, 'dashboard'])->name('dashboard');
});

In this way, you can call it through route('admin.dashboard') , the naming is clearer and easy to maintain.


Basically that's it. The core of Route Groups is "reuse" and "group management". Although it is simple to write, it can significantly improve the maintainability of the route if used properly.

The above is the detailed content of How to define and use Route Groups in Laravel.. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1596
276
How to implement a referral system in Laravel? How to implement a referral system in Laravel? Aug 02, 2025 am 06:55 AM

Create referrals table to record recommendation relationships, including referrals, referrals, recommendation codes and usage time; 2. Define belongsToMany and hasMany relationships in the User model to manage recommendation data; 3. Generate a unique recommendation code when registering (can be implemented through model events); 4. Capture the recommendation code by querying parameters during registration, establish a recommendation relationship after verification and prevent self-recommendation; 5. Trigger the reward mechanism when recommended users complete the specified behavior (subscription order); 6. Generate shareable recommendation links, and use Laravel signature URLs to enhance security; 7. Display recommendation statistics on the dashboard, such as the total number of recommendations and converted numbers; it is necessary to ensure database constraints, sessions or cookies are persisted,

How to use accessors and mutators in Eloquent in Laravel? How to use accessors and mutators in Eloquent in Laravel? Aug 02, 2025 am 08:32 AM

AccessorsandmutatorsinLaravel'sEloquentORMallowyoutoformatormanipulatemodelattributeswhenretrievingorsettingvalues.1.Useaccessorstocustomizeattributeretrieval,suchascapitalizingfirst_nameviagetFirstNameAttribute($value)returningucfirst($value).2.Usem

What are Repository Contracts in Laravel? What are Repository Contracts in Laravel? Aug 03, 2025 am 12:10 AM

The Repository pattern is a design pattern used to decouple business logic from data access logic. 1. It defines data access methods through interfaces (Contract); 2. The specific operations are implemented by the Repository class; 3. The controller uses the interface through dependency injection, and does not directly contact the data source; 4. Advantages include neat code, strong testability, easy maintenance and team collaboration; 5. Applicable to medium and large projects, small projects can use the model directly.

How to integrate React with Laravel? How to integrate React with Laravel? Jul 30, 2025 am 04:05 AM

SetupLaravelasanAPIbackendbyinstallingLaravel,configuringthedatabase,creatingAPIroutes,andreturningJSONfromcontrollers,optionallyusingLaravelSanctumforauthentication.2.ChoosebetweenastandaloneReactSPAservedseparatelyorusingInertia.jsfortighterLaravel

Using Form Requests for Validation in Laravel. Using Form Requests for Validation in Laravel. Jul 30, 2025 am 05:04 AM

Use FormRequests to extract complex form verification logic from the controller, improving code maintainability and reusability. 1. Creation method: Generate the request class through the Artisan command make:request; 2. Definition rules: Set field verification logic in the rules() method; 3. Controller use: directly receive requests with this class as a parameter, and Laravel automatically verify; 4. Authorization judgment: Control user permissions through the authorize() method; 5. Dynamic adjustment rules: dynamically return different verification rules according to the request content.

How to use subqueries in Eloquent in Laravel? How to use subqueries in Eloquent in Laravel? Aug 05, 2025 am 07:53 AM

LaravelEloquentsupportssubqueriesinSELECT,FROM,WHERE,andORDERBYclauses,enablingflexibledataretrievalwithoutrawSQL;1.UseselectSub()toaddcomputedcolumnslikepostcountperuser;2.UsefromSub()orclosureinfrom()totreatsubqueryasderivedtableforgroupeddata;3.Us

How to create a RESTful API with Laravel? How to create a RESTful API with Laravel? Aug 02, 2025 pm 12:31 PM

Create a Laravel project and configure the database environment; 2. Use Artisan to generate models, migrations and controllers; 3. Define API resource routing in api.php; 4. Implement the addition, deletion, modification and query methods in the controller and use request verification; 5. Install LaravelSanctum to implement API authentication and protect routes; 6. Unify JSON response format and handle errors; 7. Use Postman and other tools to test the API, and finally obtain a complete and extensible RESTfulAPI.

How to handle recurring payments with Laravel Cashier? How to handle recurring payments with Laravel Cashier? Aug 06, 2025 pm 01:38 PM

InstallLaravelCashierviaComposerandconfiguremigrationandBillabletrait.2.CreatesubscriptionplansinStripeDashboardandnoteplanIDs.3.CollectpaymentmethodusingStripeCheckoutandstoreitviasetupintent.4.SubscribeusertoaplanusingnewSubscription()anddefaultpay

See all articles