在laravel 5.4中向控制器添加多个中间件

时间:2017-10-09 07:26:11

标签: php laravel authentication

我有一个我想要由两个不同的警卫访问的功能,如果用户或管理员登录他/她可以访问该功能

如果我这样做,则需要登录人员(用户和管理员)才能访问该功能

class HomeController  extends Controller
{
    public function __construct()
        {
            $this->middleware('auth')->only('showABC');
            $this->middleware('auth:hr');
    }
}

但我希望如果记录了两种类型中的任何一种,他/她可以访问showABC方法。 我需要使用" OR"而不是" AND"

1 个答案:

答案 0 :(得分:1)

我建议您制作自己的中间件,您可以使用默认方法handle编写身份验证代码。然后,您只需要调用该中间件即可让任何一个用户通过身份验证。

app/Http/Middleware/CustomAuthentiation.php内制作一个中间件 并在那里写下你的逻辑,就像这个片段:

class CustomAuthentiation
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        // Write your authentication code here and then in last lines, if all is good, forward the execution ahead. Like :
        if (Auth::guard($guard)->check()) {
            return redirect('/home');
        }

        return $next($request);
    }
}

然后将其添加到$routeMiddleware的Kernel.php文件中的app/Http/Kernel.php数组中,如下所示:

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'myAuth' => \App\Http\Middleware\CustomAuthentiation::class  // Here is your middleware..
        ];

然后,您可以在routes/web.php中绑定此中间件,如下所示:

Route::middleware('myAuth')->post('login', 'LoginController@LoginUser');

希望这会有所帮助。