Laravel导航栏用户头像显示异常:Undefined variable $user问题求助
解决方案
问题根源
你的代码在仪表盘首页正常显示,是因为该页面的控制器传递了$user变量;但其他页面的控制器未传递这个变量,导致出现Undefined variable $user错误。后续添加@auth判断后虽避免了报错,但依然使用未定义的$user变量,因此头像无法渲染。
修复方案
直接在Blade模板中使用auth()->user()获取登录用户实例,替代依赖控制器传递的$user变量,无需在每个控制器重复传参,即可在所有页面正常工作:
@if(auth()->check() && !request()->routeIs('user.*')) <li> <a class="navbar-user__thumb"> <img src="{{ getImage(getFilePath('userProfile') . '/' . auth()->user()->image, null, true) }}" alt="profile-image" width="50" height="50"> </a> </li> @endif
额外优化(避免空值报错)
若用户可能未上传头像(image字段为空),可添加空值判断,防止生成无效图片路径:
@if(auth()->check() && !request()->routeIs('user.*') && auth()->user()->image) <li> <a class="navbar-user__thumb"> <img src="{{ getImage(getFilePath('userProfile') . '/' . auth()->user()->image, null, true) }}" alt="profile-image" width="50" height="50"> </a> </li> @endif
备选方案:全局共享用户变量
如果你更倾向于使用$user变量,可在App\Providers\AppServiceProvider的boot方法中全局共享登录用户,让所有视图直接调用$user:
use Illuminate\Support\Facades\View; public function boot() { // 仅在用户登录时共享变量 if (auth()->check()) { View::share('user', auth()->user()); } }
之后你原来的代码结合正确判断即可正常工作:
@if(auth()->check() && !request()->routeIs('user.*')) <li> <a class="navbar-user__thumb"> <img src="{{ getImage(getFilePath('userProfile') . '/' . $user->image, null, true) }}" alt="profile-image" width="50" height="50"> </a> </li> @endif
内容的提问来源于stack exchange,提问作者Byron Moola
相关产品推荐
相关产品推荐

