有人知道如何在laravel 5.8.15(或简称5.8)中的身份验证中间件的redirectTo()
方法中使用防护措施吗?
我收到此错误
“ App \ Http \ Middleware \ Authenticate :: redirectTo($ request,$ guards)的声明应与Illuminate \ Auth \ Middleware \ Authenticate :: redirectTo($ request)兼容”
use Illuminate\Support\Facades\Route;
protected function redirectTo($request, $guards)
{
if (! $request->expectsJson()) {
if (array_first($this->guards) === 'admin') {
return route('admin.login');
}
return route('login');
}
}
//Updated code but still getting error
//Error:: Declaration of App\Http\Middleware\Authenticate::handle($request,
Closure $next, $guard = NULL) should be compatible with
Illuminate\Auth\Middleware\Authenticate::handle($request, Closure $next,
...$guards)
//Code
....
use Closure;
use Illuminate\Support\Facades\Auth;
....
public function handle($request, Closure $next, $guard = null)
{
switch ($guard) {
case 'admin':
if (Auth::guard($guard)->check()) {
return redirect()->route('admin.login');
}
break;
default:
if (Auth::guard($guard)->check()) {
return redirect('/login');
}
break;
}
return $next($request);
}
答案 0 :(得分:0)
像这样,然后根据您的情况重定向
public function handle($request, Closure $next)
{
switch ($this->getGuard()) {
case 'admin':
if (!Auth::guard($guard)->check()) {
return redirect()->route('admin_login');
}
break;
case 'vendor':
if (!Auth::guard($guard)->check()) {
return redirect()->route('vendor_login');
}
break;
case 'user':
if (Auth::guard($guard)->check()) {
return redirect()->route('user_login');
}
break;
default:
if (Auth::guard($guard)->check()) {
return redirect('/login');
}
break;
}
return $next($request);
}
答案 1 :(得分:0)
将render($request, Exception $exception)
中的App/Exceptions/Handler.php
修改为如下所示:
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
if(get_class($exception) != 'Illuminate\Auth\AuthenticationException'){
return parent::render($request, $exception);
}
$guard = Arr::get($exception->guards(),0);
switch ($guard){
case 'admin':
return redirect(route('admin.login'));
break;
default:
return redirect(route('login'));
break;
}
}