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

Laravel使用Auth::attempt登录时如何单独返回用户不存在错误

解决方案

你可以先根据提交的用户名查询用户是否存在,再校验密码,即可拆分两种错误场景,实现代码如下:

// 先根据提交的用户名查询用户记录
$user = \App\Models\User::where('user_name', $request->user_name)->first();

// 用户不存在时直接返回专属提示
if (!$user) {
    return redirect()->back()->with('status', '用户不存在!');
}

// 用户存在时再校验账号密码
$credentials = [
    'user_name' => $request->user_name,
    'password' => $request->password,
];

if (Auth::attempt($credentials)) {
    return redirect()->route('admin.dashboard');
}

// 走到此处说明用户存在但密码错误
return redirect()->back()->with('status', '密码错误!');

注意:该实现会暴露系统中已注册的用户名,存在被攻击者枚举有效账号的安全风险,请根据业务的安全要求评估是否使用。

内容的提问来源于stack exchange,提问作者Tomato

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 10:24:03