重定向后未保留会话数据 [英] Session data not preserved after redirection

查看:197
本文介绍了重定向后未保留会话数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一些自定义Flash消息,并且在重定向后会话数据被破坏时遇到了一些问题.

I'm trying to implement some custom flash messages and I'm having some issues with the session data being destroyed after a redirect.

这是我创建即时消息的方式:

Here's how I create my flash messages :

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

这是flash()函数的声明:

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

这是我使用SweetAlerts检查会话/显示Flash消息的方式.该代码包含在我要在所有Blade模板中扩展的主布局文件的底部.

And here is how I'm checking the session/displaying the flash messages, using SweetAlerts. This code is included at the bottom of the main layout file that I'm extending in all my Blade templates.

@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()函数,则上面的代码将起作用,如下所示:

The code above will work if I call the flash() function before displaying a view, like so :

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

但是,如果在重定向到另一个页面之前调用它,它将无法正常工作,例如:

However, it will not work if I call it before doing a redirect to another page, like so :

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

为什么会话数据在重定向时丢失?如何使其持久存在,以便显示即时消息?

Why is the session data lost on redirect? How can I make it persists so that I can display my flash message?

推荐答案

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

I found out that it is necessary to apply the web middleware on all routes. Drown has mentioned to do so, but since March 23st 2016, Taylor Otwell changed the default RouteServiceProvider at https://github.com/laravel/laravel/commit/5c30c98db96459b4cc878d085490e4677b0b67ed

通过更改,将Web中间件自动应用于所有路由.如果现在在route.php中再次应用它,您将看到web在路由列表(php artisan route:list)上出现两次.这恰好使闪存数据被丢弃.

By that change the web middleware is applied automatically to all routes. If you now apply it again in your routes.php, you will see that web appears twice on the route list (php artisan route:list). This exactly makes the flash data discard.

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

这篇关于重定向后未保留会话数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆