laravel 5中间件,参数为

时间:2015-06-13 18:21:41

标签: php laravel laravel-5 laravel-validation

我是Laravel 5中的绝对初学者。

我创建了一个名为BeforeMiddleware的中间件类,该类的蓝图在下面。

class BeforeMiddleware {
    public function handle($request, Closure $next, $role)
    {
        if($request->user()->hasRole($role)){
            return redirect('/pensions');
        }
        return $next($request);
    }
}

在kernel.php中注册为

protected $routeMiddleware = [
        'auth' => 'App\Http\Middleware\Authenticate',
        'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
        'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
        'role' => 'App\Http\Middleware\BeforeMiddleware',
    ];

用户模型位于

之下
class User extends Model {
    public function hasRole($name)
    {
        return ($this->role->name == $name) ? true : false;
    }

    public function role()
    {
        return $this->belongsTo('App\Models\Role');
    }
}

以及routes.php中的用法如下。

Route:get('/reporting', [ 'middleware' => 'role:Owner', 'uses' => function(){
    return 'secret data only be viewable by the owners';
}]);

如果我在浏览器/reporting中打开它,我会收到以下错误。

ReflectionException in Container.php line 776:
Class role:Owner does not exist

HOWEVER 如果我在中间件中硬编码'Owner'并删除$role参数,并将其从现在看起来像这样的路线中删除。

BeforeMiddleware.php

class BeforeMiddleware {
    public function handle($request, Closure $next, $role)
    {
        if($request->user()->hasRole('Owner')){
            return redirect('/pensions');
        }
        return $next($request);
    }
}

routes.php文件

Route:get('/reporting', [ 'middleware' => 'role', 'uses' => function(){
        return 'secret data only be viewable by the owners';
    }]);

它按预期工作......

因此我的问题是如何在使用中间件控制路径时传递该参数

任何想法?

2 个答案:

答案 0 :(得分:2)

如果您仔细阅读Middleware Documentation,您会注意到这一行

  

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

因此,如果你的中间件类被称为BeforeMiddleware,那么中间件定义的第一部分应该是before然后是:,之后你可以定义你的路由参数,分开用逗号,像这样:

Route:get('/reporting', [ 'middleware' => 'before:Owner', 'uses' => function(){
    return 'secret data only be viewable by the owners';
}]);

答案 1 :(得分:1)

由于您使用的是Laravel 5.0,我建议您为角色创建单独的中间件。

<强> Kernel.php

'owner' => 'App\Http\Middleware\OwnerMiddleware',

<强> OwnerMiddleware

public function handle($request, Closure $next)
{
    if($request->user()->hasRole('Owner')){
        return redirect('/pensions');
    }
    return $next($request);
}

然后在 routes.php

Route:get('/reporting', [ 'middleware' => 'owner', 'uses' => function(){
    return 'secret data only be viewable by the owners';
}]);