如何解决从 $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');
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。