Laravel 9中如何用Inertia.js重定向到带用户名Prop的欢迎页
解决方案:登录后跳转并传递用户信息的正确方式
针对你遇到的问题,核心是要遵循Post/Redirect/Get (PRG) 模式避免表单重复提交,同时确保目标页面能正确获取用户数据。以下是具体修正步骤:
1. 修改登录控制器逻辑
登录验证通过后,不要直接返回Inertia组件,而是重定向到Welcome命名路由。由于已经通过Auth::attempt()完成登录,无需手动传递用户名——auth中间件会确保用户身份已被认证,后续直接从Auth facade获取即可。
public function login(Request $request) { $credentials = $request->only('email', 'password'); if (Auth::attempt($credentials)) { // 重定向到Welcome路由,遵循PRG模式 return redirect()->route('Welcome'); } else { return back()->with('message','Authentication Failed'); } }
2. 更新Welcome路由的组件数据传递
在Welcome路由的闭包中,直接从Auth获取已登录用户,并作为props传递给Inertia组件。这样既保证URL正确跳转至/Welcome,又能让组件拿到用户数据。
Route::get('/Welcome', function () { return inertia('Welcome', [ 'username' => Auth::user() ]); })->name('Welcome')->middleware('auth', 'AuthenticateCustom');
3. Vue组件接收Props
在Welcome.vue中定义props接收用户数据即可:
<template> <div class="welcome-container"> <h1>欢迎回来,{{ username.name }}</h1> </div> </template> <script setup> import { defineProps } from 'vue'; const props = defineProps({ username: { type: Object, required: true } }); </script>
问题根源解释
- 直接返回
Inertia('Welcome'):本质是在POST请求/Login的上下文里渲染组件,浏览器URL不会更新,且刷新页面会重复提交登录表单,违反PRG设计原则。 redirect()->with('username'):with()会将数据存入session闪存,但Inertia不会自动将session闪存数据映射为组件props,必须在目标路由中手动取出并传递。不过这种方式不如直接从Auth获取可靠,因为用户已登录,Auth::user()始终可用。
内容的提问来源于stack exchange,提问作者Muhammad Khan
相关产品推荐
相关产品推荐

