admin管理员组

文章数量:1287655

What I need is to use prefix() with Middleware simultaneously within Laravel.

For example this code:

Route::prefix('admin')->group(function () {
    Route::get('/users', function () {
        // Matches The "/admin/users" URL
    });
});

What I want is to use prefix() and Middleware simultaneously.

But I have no idea how to integrate them into Laravel 11.

In previous versions, it was done like this:

Route::group(['prefix' => 'post', 'middleware' => ['auth']], function(){
        Route::get('all','Controller@post');
        Route::get('user','Controller@post');
    })

But how do I do that with my current Laravel version 11?

What I need is to use prefix() with Middleware simultaneously within Laravel.

For example this code:

Route::prefix('admin')->group(function () {
    Route::get('/users', function () {
        // Matches The "/admin/users" URL
    });
});

What I want is to use prefix() and Middleware simultaneously.

But I have no idea how to integrate them into Laravel 11.

In previous versions, it was done like this:

Route::group(['prefix' => 'post', 'middleware' => ['auth']], function(){
        Route::get('all','Controller@post');
        Route::get('user','Controller@post');
    })

But how do I do that with my current Laravel version 11?

Share Improve this question edited Feb 25 at 9:20 hakre 198k55 gold badges447 silver badges854 bronze badges Recognized by PHP Collective asked Feb 23 at 13:48 zockchinzockchin 938 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

In Laravel 11, you can chain both prefix() and middleware() methods before defining your route group. Here's how to achieve the same behavior as the previous version's array syntax:

Route::prefix('post')->middleware('auth')->group(function () {
    Route::get('all', [Controller::class, 'post']);
    Route::get('user', [Controller::class, 'post']);
});

For multiple middleware:

Route::middleware(['auth', 'admin'])
     ->prefix('admin')
     ->group(function () {
         // Your routes here
     });

You can also chain other route group features:

Route::prefix('api')
     ->middleware('api')
     ->domain('api.example')
     ->name('api.')
     ->group(function () {
         // Your API routes
     });

This fluent interface approach is the recommended way in Laravel 11 for grouping routes with shared configuration. The old array-based syntax has been deprecated in favor of this more readable method chaining syntax.

https://www.slingacademy/article/route-prefixing-and-grouping-in-laravel-a-complete-guide/
https://www.devgem.io/posts/how-to-use-prefix-with-middleware-in-laravel-11

本文标签: phpUsing Middleware and Prefix or any other parameter simultaneously in Route GroupsStack Overflow