我正在尝试实现一些自定义闪存消息,并且在重定向后会话数据被破坏时遇到了一些问题。
以下是我创建我的 Flash 消息的方法:
flash('Your topic has been created.');
这是flash()
函数的声明:
function flash($message, $title = 'Info', $type = 'info')
{
session()->flash('flash', [
'message' => $message,
'title' => $title,
'type' => $type,
]);
}
这是我使用 SweetAlerts 检查会话/显示闪存消息的方式。此代码包含在我在所有 Blade 模板中扩展的主布局文件的底部。
@if(Session::has('flash'))
<script>
$(function(){
swal({
title: '{{ Session::get("flash.title") }}',
text : '{{ Session::get("flash.message") }}',
type : '{{ Session::get("flash.type") }}',
timer: 1500,
showConfirmButton: false,
})
});
</script>
@endif
flash()
如果我在显示视图之前调用该函数,上面的代码将起作用,如下所示:
public function show($slug)
{
flash('It works!');
return view('welcome');
}
但是,如果我在重定向到另一个页面之前调用它,它将不起作用,如下所示:
public function show($slug)
{
flash('It does not work');
return redirect('/');
}
为什么重定向时会话数据丢失?我怎样才能让它持续存在,以便我可以显示我的 Flash 消息?