Laravel 7 中间件 'except' 规则在控制器中不起作用

Laravel 7 middleware 'except' rule not working in controller

如果登录,我想阻止 /dashboard/login 地址。 如果注销我想允许访问 /dashboard/login 地址

我写的代码不工作。 我该如何解决 Laravel 7.

的这个问题

web.php

Route::get('/dashboard/', 'DashboardController@home')->middleware('admin');
Route::get('/dashboard/login', 'DashboardController@login')->name('dashboard_login');
Route::post('dashboard/post-login','DashboardController@postLogin');

仪表板控制器

class DashboardController extends Controller
{
    public function __construct()
    {
      $this->middleware('auth', ['except' => ['dashboard_login']]);
    }
    public function home(){
       return view('dashboard.home');
    }
    public function login(){
       return view('dashboard.login');
    }

  }

管理中间件

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class Admin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::check() &&  (auth()->user()->role == 1 or auth()->user()->role == 2)){
            return $next($request);
        }
        return redirect('home')->with('error',"You don't have admin access.");
    }
}

您可能需要从

切换
$this->middleware('auth', ['except' => ['dashboard_login']]);

$this->middleware('auth')->except('login');

看来 documentation

我想你想使用 'guest' 中间件。

Route::get('/dashboard/login', 'DashboardController@login')->middlware('guest')->name('dashboard_login');

如果通过身份验证,用户将被重定向到定义的路由。

可以在 app/Http/Middleware/RedirectIfAuthenticated.php

中调整行为

我想到了这个选项

web.php

Route::get('/dashboard', 'DashboardController@home')->middleware('auth','admin'); //if not logged , redirect to auth default login then if logged, AdminMiddleware checking role

仪表板控制器:

class DashboardController extends Controller
{
    public function home(){
       return view('dashboard.home');
    }

    public function login(){
       if(auth()->check())
          return redirect()->route('or url where you want to redirect if user already logged');
       return view('dashboard.login');
    }

}

如果你还想检查DashboardController中的中间件,就不用管web.php了,那就

仪表板控制器:

class DashboardController extends Controller
{
    public function __construct()
    {
       $this->middleware('auth')->except('login');
       //here what u asked, you can remove middleware in route
       //$this->middleware('admin')->only('home');
    }
    public function home(){
       return view('dashboard.home');
    }

    public function login(){
       if(auth()->check())
          return redirect()->route('or url where you want to redirect if user already logged');
       return view('dashboard.login');
    }

}