Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session data not preserved after redirection

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.');

Here's the declaration of the flash() function :

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

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

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?

like image 398
Drown Avatar asked Dec 23 '15 15:12

Drown


2 Answers

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

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.

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

like image 183
raphael Avatar answered Nov 18 '22 06:11

raphael


It turns out that with Laravel 5.2, the routes have to be wrapped in the web middleware for the session to work properly.

This fixed it :

Route::group(['middleware' => ['web']], function () {
    // ...
    Route::post('/topics/{slug}/answer', 'PostsController@answer');
    Route::post('/topics/{slug}/unanswer', 'PostsController@unanswer');
    Route::post('/topics/{slug}/delete', 'PostsController@delete');
});
like image 6
Drown Avatar answered Nov 18 '22 06:11

Drown