我希望我的/dashboard页面在2个不同的用户类型是一个不同的面板。如果未登录,则返回主屏幕。我创建了2个中间件来检查登录用户是否为"雇主"。或";employee"。无论我做什么,我似乎都做不到,已经两天了。我按照一些非常粗略的教程创建了中间件和路由,它可能会伤害你的眼睛,注意。
我的路线:
Route::get('/dashboard', function () {
return view('welcome');
})->name('welcome');
Route::prefix('admin')->middleware([AppHttpMiddlewareisEmployer::class])->group( function () {
Route::get("/dashboard", function (){
return view("employer.dashboard");
})->name("dashboard");
});
Route::prefix('store')->middleware([AppHttpMiddlewareisEmployee::class])->group( function(){
Route::get("/dashboard", function (){
return view("employee.dashboard");
})->name("dashboard");
});
isEmployee中间件:
<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
class isEmployee
{
public function handle(Request $request, Closure $next)
{
if(Auth::user())
{
if (Auth::user()->role == "employee")
{
return $next($request);
}
}
return response()->view('welcome');
}
}
isEmployer中间件:
<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
class isEmployer
{
public function handle(Request $request, Closure $next)
{
if(Auth::user())
{
if (Auth::user()->role == "employer")
{
return $next($request);
}
}
return response()->view('welcome');
}
}
我想实现的是:
如果未登录:返回欢迎视图
如果作为雇主登录:返回雇主。仪表板视图
如果以雇员身份登录:返回雇员。仪表板视图
让我们从重构开始:
-
让你的
routes/web.php
更容易读:Route::view('/dashboard', 'welcome')->name('welcome'); Route::prefix('admin')->name('admin.')->middleware('role:employer')->group(function() { Route::view('/dashboard', 'employer.dashboard')->name("dashboard"); }); Route::prefix('store')->name('store.')->middleware('role:employee')->group(function() { Route::view('/dashboard', 'employee.dashboard')->name("dashboard"); });
-
现在让我们创建一个中间件,它不仅会检查一个角色,还会检查您作为参数提供的任何角色:
<?php namespace AppHttpMiddleware; use Closure; use IlluminateHttpRequest; use IlluminateSupportFacadesAuth; class HasRole { public function handle(Request $request, Closure $next, string $role) { if (Auth::user()?->role != $role) { return redirect()->route('welcome'); } return $next($request); } }
-
现在,在你的
app/Http/Kernel.php
中创建一个别名,这样你就可以像我在路由文件role:<role_here>
中写的那样使用它:protected $routeMiddleware = [ // ... 'role' => AppHttpMiddlewareHasRole::class, ];
现在回答你的问题——如何为一条路由使用多个中间件。很简单:
$route->middleware(['middleware1', 'middleware2']);
您可以将它们附加到组或单个路由:
Route::prefix('some_group')->middleware(['middleware1', 'middleware2'])->group(function() {
Route::view("some.view")->middleware('middleware3')->name("some.view");
});
你可以在这里阅读更多关于Laravel中间件的信息,并了解什么是责任链(中间件实现的模式)。也可以看看SOLID原则,主要是DRY原则。祝你过得愉快=)