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

Laravel:在重定向状态消息中显示已认证用户名称

问题解决方法

你的问题出在错误地在PHP字符串中使用了Blade模板语法,{{ Auth::user()->name }}是Blade模板里的变量输出语法,在控制器的PHP代码里它会被当作普通文本输出,而不会解析为用户名。

可以用以下几种正确方式实现:

方法1:字符串拼接

直接用PHP的字符串拼接语法,把Auth::user()->name的值拼接到消息里:

public function authenticated()
{
    if(Auth::user()->role_as == '1') // Admin = 1
    {
        return redirect('admin/dashboard')->with('status', 'Welcome to your Admin Dashboard, ' . Auth::user()->name . '.');
    }
    else
    {
        return redirect('/home')->with('status', 'Welcome back, ' . Auth::user()->name);
    }
}

方法2:双引号字符串插值

PHP支持在双引号字符串中直接解析变量,写法更简洁:

public function authenticated()
{
    $userName = Auth::user()->name;
    
    if(Auth::user()->role_as == '1') // Admin = 1
    {
        return redirect('admin/dashboard')->with('status', "Welcome to your Admin Dashboard, {$userName}.");
    }
    else
    {
        return redirect('/home')->with('status', "Welcome back, {$userName}");
    }
}

方法3:简化逻辑写法(可选)

可以先获取用户对象,统一处理消息和跳转地址,让代码更简洁:

public function authenticated()
{
    $user = Auth::user();
    $isAdmin = $user->role_as == '1';
    
    $message = $isAdmin 
        ? "Welcome to your Admin Dashboard, {$user->name}." 
        : "Welcome back, {$user->name}";
    
    return redirect($isAdmin ? 'admin/dashboard' : '/home')->with('status', $message);
}

核心原理:Blade模板语法仅在.blade.php模板文件中生效,控制器的PHP代码必须使用PHP原生的变量引用方式来获取用户名称。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:05:41