如何在路线中添加角色?

时间:2017-08-01 06:48:48

标签: php laravel

这是我目前的路线:(也适用)

Route::get('/register', ['uses' =>  'registerController@form','as'=>'register','middleware' => 'roles', 'roles' => ['admin'] ]);

现在我想知道,当我编写像role这样的中间件时,如何使用->middleware('role')

注意:这不起作用:

Route::get('/register', 'registerController@form')->name('register')->middleware('role')->role(['admin']);

2 个答案:

答案 0 :(得分:1)

Route::get('/register', 'registerController@form')->name('register')->middleware('role:admin');

我想你想要这个

多个

Route::group(['middleware' => ['role:Normal_User,Admin']], function() {
        Route::get('/register', 'registerController@form');
    });

答案 1 :(得分:1)

  

通过将中间件名称和参数分隔为:来定义路由时,可以指定中间件参数。多个参数应以逗号分隔。

您可以制作自己的中间件:

<?php

namespace App\Http\Middleware;

use Closure;

class CheckRole
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string  $role
     * @return mixed
     */
    public function handle($request, Closure $next, $role)
    {
        if (! $request->user()->hasRole($role)) {
            // Redirect...
        }

        return $next($request);
    }

}

并称之为:

Route::get('/register', 'registerController@form')->name('register')->middleware('role:editor');

来源:https://laravel.com/docs/5.4/middleware#middleware-parameters