Laravel 9 Jetstream(Inertia)头像无法加载问题求助
问题背景
使用Laravel 9 + Jetstream + Inertia栈搭建项目,执行了标准安装流程:
laravel new testProject cd testProject composer require laravel/jetstream php artisan jetstream:install inertia npm install npm run dev php artisan serve
仅做了两项修改:
- 在
.env中配置数据库连接 - 开启
profilePhotos功能:'features' => [ // Features::termsAndPrivacyPolicy(), Features::profilePhotos(), // Features::api(), // Features::teams(['invitations' => true]), Features::accountDeletion(), ],
同时执行了php artisan storage:link创建存储软链接。
问题现象:上传头像后页面未刷新时显示正常,刷新页面后个人信息区域和右上角头部的头像均显示404错误。浏览器请求路径为storage/profile-photos/P2Fr1yHE0UenDAo5REUWEEWFcwq7esjLu0loP9Xa.png,但实际文件存储在storage/app/public/profile-photos/目录,且已通过软链接映射到public/storage/profile-photos/。
解决方案
1. 修复前端头像路径的相对/绝对路径问题
问题核心是前端渲染头像时使用了相对路径storage/xxx,而非站点根目录的绝对路径/storage/xxx。浏览器会从当前页面的URL路径下去拼接资源地址,导致路径错误。
找到项目中渲染头像的Vue组件(通常是resources/js/Pages/Profile/Partials/UpdateProfileInformationForm.vue和resources/js/Layouts/AppLayout.vue),修改img标签的src属性:
<!-- 错误示例 --> <img :src="user.profile_photo_path" alt="User Avatar" /> <!-- 正确示例 --> <img :src="`/storage/${user.profile_photo_path}`" alt="User Avatar" />
2. 后端生成完整头像URL(可选)
也可以在后端传递用户数据时直接生成完整的头像URL,避免前端拼接:
修改app/Http/Controllers/ProfileController.php中的edit或updateProfileInformation方法,使用asset()助手生成绝对URL:
public function edit(Request $request) { $user = $request->user(); $user->profile_photo_url = asset('storage/' . $user->profile_photo_path); return Inertia::render('Profile/Edit', [ 'user' => $user, 'status' => session('status'), ]); }
之后前端直接使用user.profile_photo_url即可:
<img :src="user.profile_photo_url" alt="User Avatar" />
3. 验证存储软链接有效性
重新确认软链接是否正确创建,执行:
php artisan storage:link
如果提示链接已存在,先删除public/storage目录再重新创建:
rm -rf public/storage php artisan storage:link
4. 检查APP_URL配置
确保.env文件中的APP_URL与当前开发环境一致,本地开发通常设置为:
APP_URL=http://localhost:8000
这能保证asset()助手生成正确的绝对URL。
内容的提问来源于stack exchange,提问作者Vadim Gerich

