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

Laravel中如何在登录成功提示消息中加入登录用户名称

解决方案:在登录提示中包含用户名

1. 修改UserController的登录成功逻辑

在登录验证通过后,获取当前用户的名称并拼接到提示消息中,修改后的代码如下:

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

    if(auth()->attempt($validated)){
       $request->session()->regenerate();
       // 获取登录用户名称,字段名根据用户表实际情况调整
       $userName = auth()->user()->name;
       // 拼接带用户名的提示消息
       return redirect('/')->with('information-message', "Welcome Back! ($userName)");
    }

    return redirect('login')->with('failed-message', 'Login Failed. Please Try Again!');
}

说明:auth()->user()会返回当前已登录的用户对象,这里取name字段作为用户名,如果你的用户表使用的是username或其他字段,直接替换即可。拼接好的消息通过with()存入session,供视图读取。

2. 确认视图渲染逻辑(无需修改)

你的information-message.blade.php已经正确读取session中的提示消息并渲染,保持原代码即可:

@if (session()->has('information-message'))

<div x-data="{show : true}" x-show="show" x-init="setTimeout(() => show = false, 5000)" class="flex fixed m-2 bottom-0 right-0 z-20 items-center bg-blue-700 text-white text-sm font-bold px-4 py-3" role="alert">
    <svg class="fill-current w-4 h-4 mr-2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M12.432 0c1.34 0 2.01.912 2.01 1.957 0 1.305-1.164 2.512-2.679 2.512-1.269 0-2.009-.75-1.974-1.99C9.789 1.436 10.67 0 12.432 0zM8.309 20c-1.058 0-1.833-.652-1.093-3.524l1.214-5.092c.211-.814.246-1.141 0-1.141-.317 0-1.689.562-2.502 1.117l-.528-.88c2.572-2.186 5.531-3.467 6.801-3.467 1.057 0 1.233 1.273.705 3.23l-1.391 5.352c-.246.945-.141 1.271.106 1.271.317 0 1.357-.392 2.379-1.207l.6.814C12.098 19.02 9.365 20 8.309 20z"/></svg>
    <p>{{session('information-message')}}</p>
  </div>

@endif

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 22:59:56