Laravel 路由::管理员组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39555865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:28:32  来源:igfitidea点击:

Laravel Route::group for Admins

laravelroutesadmin

提问by Okay

I would like to authentificate some routes, if the user is admin.

如果用户是管理员,我想验证一些路由。

Route::get( '/user/{data}', 'UserController@getData' );
Route::post( '/user/{data}', 'UserController@postData' );

Now, I made it inside the Controller:

现在,我在控制器中制作了它:

public function getData( $data = 'one' )
{
    if ( Auth::user()->permission == 'admin' ) {
        //...
    } else {
        //...
    }
}

public function postData( Request $request, $data = 'one' )
{
    if ( Auth::user()->permission == 'admin' ) {
        //...
    } else {
        //...
    }
}

I would like to make it with Route::group, but how can I do that in the routes.php?

我想用 Route::group 来实现,但我如何在 routes.php 中做到这一点?

回答by Alexey Mezenin

You can create middlewarewhich will check if user is an admin:

您可以创建中间件来检查用户是否是管理员:

class IsAdmin
{
    public function handle($request, Closure $next)
    {
        if (Auth::user()->permission == 'admin') {
            return $next($request);
        }

        return redirect()->route('some.route'); // If user is not an admin.
    }
}

Register it in Kernel.php:

注册它Kernel.php

protected $routeMiddleware = [
    ....
    'is.admin' => \App\Http\Middleware\IsAdmin::class,
];

And then apply it to a route group:

然后将其应用于路由组:

Route::group(['middleware' => 'is.admin'], function () {
    Route::get('/user/{data}', 'UserController@getData');
    Route::post('/user/{data}', 'UserController@postData');
});

回答by Alex Mozharov

You can specify a routes group and give it a middleware

你可以指定一个路由组并给它一个中间件

https://laravel.com/docs/5.3/routing#route-groups

https://laravel.com/docs/5.3/routing#route-groups

https://laravel.com/docs/5.3/middleware

https://laravel.com/docs/5.3/middleware

https://laravel.com/docs/5.3/middleware#assigning-middleware-to-routes

https://laravel.com/docs/5.3/middleware#assigning-middleware-to-routes

Example:

例子:

routes.php

路由文件

Route::group(['middleware' => 'admin'], function () {
    Route::get( '/user/{data}', 'UserController@getData' );
    Route::post( '/user/{data}', 'UserController@postData' );
});

app/Http/Middleware/admin.php

应用程序/Http/中间件/admin.php

<?php

namespace App\Http\Middleware;

use Closure;

class Admin
{
    public function handle($request, Closure $next)
    {
        if ( Auth::user()->permission !== 'admin' ) {
            //
        } else {
            //
        }

    }
}