会话中的重定向在 Laravel 中不起作用
我正在尝试在 Laravel 中进行基本的登录会话,并且希望用户在登录后无法进入登录页面。我尝试将其重定向到主页,但如果我这样做,它仍然显示我的登录页面访问它。
我还需要添加什么吗?
这是我使用的中间件:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class UserAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if($request->path()=="login" && $request->session()->has('user'))
{
return redirect('/');
}
return $next($request);
}
}
I am trying to do a basic login session in Laravel and I want the user not to be able to go to the login page once they are logged in. I tried to redirect it to the home page but it still shows my login page if I access it.
Do I have to add anything else?
This is the middleware that I used:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class UserAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if($request->path()=="login" && $request->session()->has('user'))
{
return redirect('/');
}
return $next($request);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
确保你实际上已经注册了你的中间件(无论是在
app/Http/Kernel
中还是在路由/控制器中。还要确保你在 Laravel 的普通 HTTP 中间件之后运行中间件,否则它可能不会已启动会话/已获取用户。我不确定
$request->session()->has('user')
是您所认为的 - 这是检查是否如此会话有一个名为user
的键,您可能需要检查$request->user()
。Make sure you've actually registered your middleware (whether in
app/Http/Kernel
or with the routes/controller. Also ensure you run the middleware after Laravel's normal HTTP middleware otherwise it may not have started the session/fetched the user yet.I'm not sure
$request->session()->has('user')
is what you think it is - that's checking to see if the session has a key calleduser
. You might want to check$request->user()
instead.