我正在设置一个Web应用程序,我希望在其中区分两个路由组。两个小组都按照预期的方式工作,但是当它们合并时,其中一个小组失败了。我已经检查了L5.4网站上的文档并按照说明进行操作。经过一整天的挖掘决定问你。
这是我的routes / web.php文件:
Route::group(['middleware' => ['auth']], function () {
Route::group(['middleware' => ['medewerker']], function () {
Route::get('/urencorrectie','UrenRegelsController@urencorrectie');
});
Route::group(['middleware' => ['officemanager']], function () {
Route::get('/', 'DashboardController@index');
Route::post('/', 'DashboardController@index');
Route::get('/profile', function(){
return view('profile');});
});
});
Auth::routes();
Route::get('/home', 'HomeController@index');
为了启用角色,我将Rolid列添加到用户模型中。 Rol 1是officemanager,角色3是员工。
然后在随后的中间件中找到employee.php:
namespace App\Http\Middleware;
use Closure;
use Auth;
class Employee
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::user()->Rolid=='3')
{
return $next($request);
}
else
{
return redirect('/home');
}
}
}
Middleware officemanager.php文件包含:
namespace App\Http\Middleware;
use Closure;
use Auth;
class Officemanager
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$user=Auth::user();
if(Auth::user()->Rolid=='1')
{
return $next($request);
}
else
{
return redirect('/home');
}
}
}
代码生成以下结果: - 当Officemanager登录时,他/她将被重定向到正确的路由。一切正常。 - 当员工登录时,他/她被重定向到/ home重定向(routing / web.php文件的底部)。
非常欢迎任何线索或帮助。有点坚持可能是基本的东西。
[UPDATE]
在kernel.php中,两个类都被映射:
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'officemanager' => \App\Http\Middleware\Officemanager::class,
'employee' => \App\Http\Middleware\Employee::class,
];
答案 0 :(得分:1)
我唯一可以想到的是员工的Rolid
不是3 - 所以尝试调试它。
通常,不建议在代码中依赖DB ID,因为它们可以在不同环境之间进行更改。我会为user
模型添加一个关系并检查rol名称:
User model:
public function role()
{
return $this->belongsTo('App\Role', 'Rolid');
}
员工middlaware
class Employee
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::user()->role->name == 'employee')
{
return $next($request);
}
else
{
return redirect('/home');
}
}
}
Office manger中间件:
class Officemanager
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::user()->role->name == 'officemanager')
{
return $next($request);
}
else
{
return redirect('/home');
}
}
}