You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel登录查询构建器解决方案:登录后无法跳转首页问题排查

问题分析与解决步骤

1. 修复代码语法错误

你的代码存在语法缺失:if ($user && Hash::check(...))代码块缺少闭合的{,导致逻辑无法正常执行。修正后代码如下:

public function login(Request $request)
{
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    $email = $request->input('email');
    $password = $request->input('password');

    // 根据邮箱从数据库获取用户凭证
    $user = DB::table('users')
        ->where('email', $email)
        ->whereNull('deleted_at')
        ->first();

    if ($user && Hash::check($password, $user->password)) {
        // 如果凭证匹配,则登录成功
        // 登录成功后执行操作
        return redirect()->route('home');
    } else {
        // 如果凭证不匹配,返回登录页并提示错误
        return redirect()->back()->withInput()->withErrors(['email' => 'Invalid email or password']);
    }
}

2. 添加Laravel认证会话逻辑

这是核心问题:你仅验证了账号密码的正确性,但未调用Laravel的认证方法创建用户会话。没有有效会话的情况下,访问受auth中间件保护的home路由会被强制跳回登录页。

需要引入Auth门面,在验证通过后执行登录操作:

use Illuminate\Support\Facades\Auth;

public function login(Request $request)
{
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    $email = $request->input('email');
    $password = $request->input('password');

    // 使用Eloquent模型获取用户实例(Auth::login需要Authenticatable接口实例)
    $user = \App\Models\User::where('email', $email)
        ->whereNull('deleted_at')
        ->first();

    if ($user && Hash::check($password, $user->password)) {
        // 创建用户认证会话
        Auth::login($user);
        // 可选:如果需要"记住我"功能,可替换为下面的代码
        // $request->has('remember') ? Auth::login($user, true) : Auth::login($user);
        
        return redirect()->route('home');
    } else {
        return redirect()->back()->withInput()->withErrors(['email' => '邮箱或密码无效']);
    }
}

注意:必须使用Eloquent的User模型实例,而非DB门面返回的stdClass对象,因为Auth::login()要求传入实现Authenticatable接口的类实例(Laravel默认User模型已实现该接口)。

3. 验证路由与中间件配置

  • 确认home路由已正确配置,且该路由的auth中间件配置正常(仅当存在有效会话时允许访问)。
  • 登录路由本身不能被auth中间件保护,否则会陷入循环跳转。

4. 调试排查建议

如果问题仍存在,可通过以下方式排查:

  • 在if ($user && Hash::check(...))代码块内添加dd('登录验证通过'),确认是否进入登录成功分支。
  • 检查浏览器Session存储,确认是否存在laravel_session及login_web_xxx等认证相关Cookie。
  • 查看home路由的中间件逻辑,确认是否有其他规则导致跳转回登录页。

内容的提问来源于stack exchange,提问作者Talidah Nur Keyesa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 15:01:15