使用 Laravel Vue Inertia 堆栈中的数据重定向路由 [英] Redirect route with data in Laravel Vue Inertia stack
问题描述
在我的控制器中我有
公共函数库(Request $request){$postData = $this->validate($request, ['名称' =>'必需的','状态' =>'必填 |布尔值']);房间::创建(['名称' =>$postData['name'],'活跃' =>$postData['状态'],]);$message = "添加房间";return redirect::route('rooms.index', ['msg' => $message]);}
我在道具中使用了'msg'
props:['rooms','errors','msg']
但是对于 {{msg}} 给出未定义而不是任何消息.
您将 msg
作为参数传递给路由,而不是作为 Inertia::render<的参数/code> 调用.并且由于您正在重定向,您可能希望将消息闪存到会话并在
HandleInertiaRequests
中间件上处理它.查看文档中的示例.
所以,首先你重定向到 rooms.index
闪烁消息:
return redirect()->route('rooms.index')->with('message', 'My message');
然后,Inertia 请求 rooms.index
路由作为 XHR 请求,在它到达您的控制器之前,它会通过 HandleInertiaRequests
中间件.
class HandleInertiaRequests 扩展中间件{公共功能共享(请求 $request){返回 array_merge(parent::share($request), ['闪光' =>['消息' =>fn() =>$request->session()->get('message')],]);}}
现在您可以通过以下方式在您的组件中访问它:
<主要><标题></标题><内容><div v-if="$page.props.flash.message";类=警报">{{ $page.props.flash.message }}
<插槽/></内容><页脚></页脚></main></模板>
In my controller i have
public function store(Request $request)
{
$postData = $this->validate($request, [
'name' => 'required',
'status' => 'required | boolean'
]);
Room::create([
'name' => $postData['name'],
'active' => $postData['status'],
]);
$message = "Room Added";
return redirect::route('rooms.index', ['msg' => $message]);
}
and i used 'msg' in my props
props:['rooms','errors','msg']
But for {{msg}} gives undefined and not any message.
You're passing msg
as a param to your route, not as a param to your Inertia::render
call. And since you're redirecting, you probably want to flash the message to the session and handle it on the HandleInertiaRequests
middleware. Look into the example in the documentation.
So, first you redirect to rooms.index
flashing the message:
return redirect()->route('rooms.index')->with('message', 'My message');
Then, Inertia requests the rooms.index
route as a XHR request and before it hits your Controller, it passes through the HandleInertiaRequests
middleware.
class HandleInertiaRequests extends Middleware
{
public function share(Request $request)
{
return array_merge(parent::share($request), [
'flash' => [
'message' => fn () => $request->session()->get('message')
],
]);
}
}
Now you can access it in your component via:
<template>
<main>
<header></header>
<content>
<div v-if="$page.props.flash.message" class="alert">
{{ $page.props.flash.message }}
</div>
<slot />
</content>
<footer></footer>
</main>
</template>
这篇关于使用 Laravel Vue Inertia 堆栈中的数据重定向路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!