从 $request 获取请求的中间件列表?

Get Requested middleware list from $request?

在我使用 Laravel 8 使用 vue+ inertia + fortify 包创建的项目中,我使用了两个守卫,一个用于普通用户,一个用于管理员。但是只有一个登录视图重定向。

我只想向普通用户显示不同的登录信息,并向管理员显示另一个登录信息。它应该由路由中使用的中间件检测。我可以过滤它,如果我可以从那里得到请求的守卫名字。

这是我的示例路线:

<?php
//'auth:users' is normal users guard

 Route::group(['middleware' => 'auth:users'], function () {
            Route::prefix('/account')->name('account.')->group(function () {
                Route::get('/', [AccountController::class, 'index'])->name('index');
});});

//'auth:web' is admin users guard

 Route::group(['middleware' => 'auth:web'], function () {
      Route::prefix('/admin')->name('admin.')->group(function () {
            Route::prefix('/account')->name('account.')->group(function () {
                Route::get('/', [AdminAccountController::class, 'index'])->name('index');
   });
 });
});

授权中间件:

<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        // both request coming to here i want get middlware name from here
   //       if('auth:web'){
 //redirect to adimin login
 //         }else{
 //redirect to userlogin
 //}

       
        if (! $request->expectsJson()) {
            return route('admin.login');
        }
    }
}

您可以使用 request()->route()->computedMiddleware 获取用于当前路由的所有中间件的列表,因此您的代码将是:

<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if ($request->route() && in_array('auth:web', $request->route()->computedMiddleware??[]) {
         // redirect to admin login
       } else {
         // redirect to admin login
       }
 
       
        if (! $request->expectsJson()) {
            return route('admin.login');
        }
    }
}