Laravel 5.2 中使用相同方法的多个控制器中间件

multiple controller middleware usiing same methods in Laravel 5.2

我正在尝试将同一控制器的某些方法与不同的中间件一起使用,例如让管理员和用户在同一控制器中使用索引和创建方法。所以我做了一个管理员守卫和一个用户守卫。

这是我的 AdminMidleware

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class AdminMidleware
{

    public function handle($request, Closure $next)
    {
        if (Auth::guard('admin')->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('/');
            }
        }

        return $next($request);
    }
}

我的用户中间件

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class UserMiddleware
{

    public function handle($request, Closure $next)
    {
        if (Auth::guard('user')->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('/');
            }
        }

        return $next($request);
    }
}

它们都在 $routeMiddleware

的 kernel.php 中
'admin' => \App\Http\Middleware\AdminMidleware::class,
'user' => \App\Http\Middleware\UserMiddleware::class,

如果我使用这个,我可以让只有管理员可以访问这些方法,而且它有效,你必须以管理员身份登录才能使用这些方法。

public function __construct(){
   $this->middleware('admin', ['only' => [
      'index',
      'create',
   ]]);
}

这是为了让用户和管理员能够在同一个控制器中使用索引和创建方法,作为第一个参数发送一个包含管理员和用户中间件的数组,

public function __construct(){
   $this->middleware(['admin', 'user'], ['only' => [
      'index',
      'create',
   ]]);
}

但是,它不起作用,它实际上使任何人都无法使用这些方法,你能帮我把它弄好吗?我做错了什么?

由于您的中间件是相同的,除了使用的 guard,您可以尝试制作一个 auth 中间件来模仿新版本 auth 中间件 Laravel。这会让你将多个守卫作为参数传递给中间件。

public function handle($request, Closure $next)
{
    // get guards or use 'null' (default guard)
    $guards = array_slice(func_get_args(), 2) ?: [null];

    // spin through guards to find one that checks out
    foreach ($guards as $guard) {
        if (Auth::guard($guard)->check()) {
            // if we have a guard name, not null
            if ($guard) {
                // use this guard as the default
                Auth::shouldUse($guard);
            }

            // we have an authed user from some guard move along
            return $next($request);
        }
    }

    // handle no authed user
    if ($request->ajax() || $request->wantsJson()) {
        return response('Unauthenticated.', 401);
    }

    return redirect()->guest('/');
}

它将遍历所有通过的守卫,如果其中任何一个解决了用户问题,该守卫将成为 Auth 将使用的默认守卫。

$this->middleware('thatmiddleware:user,admin');

类似的东西应该有用。