php - 重定向后 session 数据未保留

标签 php laravel session redirect laravel-5.2

我正在尝试实现一些自定义的 flash 消息,但在重定向后 session 数据被销毁方面遇到了一些问题。

以下是我创建即显消息的方式:

flash('Your topic has been created.');

这是 flash() 函数的声明:

function flash($message, $title = 'Info', $type = 'info')
{   
    session()->flash('flash', [
        'message' => $message,
        'title' => $title,
        'type' => $type,        
    ]); 
}

下面是我如何使用 SweetAlerts 检查 session /显示 flash 消息。此代码包含在我在所有 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

如果我在显示 View 之前调用 flash() 函数,上面的代码将起作用,如下所示:

public function show($slug)
{
    flash('It works!');
    return view('welcome');
}

但是,如果我在重定向到另一个页面之前调用它,它将不起作用,如下所示:

public function show($slug)
{
    flash('It does not work');
    return redirect('/');
}

为什么 session 数据在重定向时丢失了?我怎样才能让它持续存在,以便我可以显示我的即时消息?

最佳答案

我发现有必要在所有路由上应用web中间件。 Drown 曾提到这样做,但自 2016 年 3 月 23 日起,Taylor Otwell 更改了默认的 RouteServiceProvider https://github.com/laravel/laravel/commit/5c30c98db96459b4cc878d085490e4677b0b67ed

通过该更改,网络中间件会自动应用于所有路由。如果现在在 routes.php 中再次应用它,您将看到 web 在路由列表 (php artisan route:list) 中出现两次。这正是使闪存数据丢弃。

另见:https://laracasts.com/discuss/channels/laravel/session-flash-message-not-working-after-redirect-route/replies/159117

关于php - 重定向后 session 数据未保留,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34438852/

相关文章:

php - 在多个子目录中使用 php include

java - Hibernate,如果不使用beginTransaction会发生什么?

php - 从 PHP 5.3 应用程序调用 mysql 存储函数

php - 我怎样才能有效地让我的脚本休眠准确的毫秒数?

php - sync or updateExistingPivot with Laravel——如何根据第三个标准进行填充

cmd - 在没有/vendor/bin/的 laravel 4 中使用 phpunit

php - Ajax post 请求仅在浏览器关闭并再次打开后才能通过

session - Node.js expressjs session 不会停留在 Firefox 中

php - 使用 PHP 解决/关闭 JIRA 中的问题

php - Dingo API - 如何在 url 中添加版本号?