代码之家  ›  专栏  ›  技术社区  ›  Junaid Masood

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

  •  -1
  • Junaid Masood  · 技术社区  · 9 年前

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

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

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

    1 回复  |  直到 9 年前
        1
  •  1
  •   Himanshu Upadhyay    9 年前

    我建议您制作自己的中间件,在那里您可以用默认方法编写身份验证代码 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 内核中的数组。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');
    

    希望这会有所帮助。