vandyczech's avatar

Session flash message not working after redirect route

I have problem with session flash message working. I have function store:

public function store( Request $request ){
        $book = new \App\Book( $request->all() );
        $book->save();
        return redirect()->route('library')->with('status', 'New book was added');
}

But I cant see the status in my view:

@if (session('status'))
     <p>{{ session('status') }}</p>
@endif 

Where I dump the session, i see the value, but in normal process i cant

0 likes
28 replies
Snapey's avatar

is get::('library....) inside a web middleware route?

1 like
shez1983's avatar

try using the facade, Session::get('status')

athulpraj's avatar

I use this method to show messages : Add this to the controller Part:

\Session::flash('msg', 'Changes Saved.' );

and this to the view part

@if(Session::has('msg'))
        <div class="alert alert-info">
            <a class="close" data-dismiss="alert">×</a>
            <strong>Heads Up!</strong> {!!Session::get('msg')!!}
        </div>
    @endif
1 like
vandyczech's avatar

But standard form should be allright, but it isn't :( Maybe LibraryController doesn't information about session status after redirect route from store ...

// How use standard redirect()->route()->with()

Route::group(['middleware' => ['web']], function () {

    Route::get('/library'       , [ 'as' => 'library'         , 'uses' => 'LibraryController@index' ]);
    Route::post('book/store'    , [ 'as' => 'store_book'      , 'uses' => 'BookController@store' ]);

}

BookController:

public function store( Request $request ){

        $book = new \App\Book( $request->all() );
        $book->save();
        return redirect()->route('library')->with('status', 'Book was added');
}

LibraryController:

public function index(){

    return view('books.index', [ 'books' => Book::all() ]);

}

books / index.blade.php

@if (session('status'))
    <p>{{ session('status') }}</p>
@endif
Leozb's avatar

@vandyczech I had the same problem Solved with to_route('name') Instead of redirect()->route('name')

Snapey's avatar

This line;

 return redirect()->route('library')->with('status', 'Book was added');

does not create session variables, it creates $status with value of 'Book was added'

You can then, in the view use {{$status}}

Note that you don't need to test it since you can use the or keyword {{$status or ''}}

Snapey's avatar

ok, my bad! I did not appreciate there was a difference between response redirect and returning a view. Makes sense though since you cannot pass data on a redirect without the session.

Snapey's avatar

@vandyczech what do you get if you put this in your view;

                    <?php echo '<pre>';var_dump(session()->all()); ?>
vandyczech's avatar
array (size=4)
    '_token' => string 'SvS6KSuqqpegGjufjV6qP3xpY2WPcuogJcvfIlSA' (length=40)
    '_previous' => 
    array (size=1)
    'url' => string 'http://example.dev/book/add' (length=27)
    'flash' => 
    array (size=2)
        'old' => 
    array (size=1)
        0 => string 'status' (length=6)
        'new' => 
    array (size=0)
        empty
    'status' => string 'Book was added' (length=11)
Snapey's avatar

Did you var_dump, that response looks really odd. It might be the formatting in the forum?

array(6) {
  ["_token"]=>
  string(40) "mrcANaOxmxtz2j86CK6eABJtlpji7JNad6Lo1lOu"
  ["url"]=>
  array(0) {
  }
  ["_previous"]=>
  array(1) {
    ["url"]=>
    string(21) "http://csdb.mac/login"
  }
  ["flash"]=>
  array(2) {
    ["old"]=>
    array(1) {
      [0]=>
      string(5) "hello"
    }
    ["new"]=>
    array(0) {
    }
  }
  ["login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d"]=>
  int(1)
  ["hello"]=>
  string(5) "world"
}

Above is an example where I redirected ->with(['hello' => 'world'])

(I get the same result if I don't pass an array, and do it as you ->with('hello', 'world');

vandyczech's avatar

What right set a session? it seems that is not working ...

Snapey's avatar

your previous dump shows that the session is being set correctly. If you placed that var_dump in your blade template where you expect to see the message then I can't see why it would not work.

are you sure this bit of your layout is actually visible?

davestewart's avatar

I've been tripped up before with empty flash data, where I've accidentally redirected twice.

Has this happened somehow? Might you have some other middleware doing something you've forgotten about, or a route making an interim redirect?

dvdheiden's avatar

You should check if you apply the web middleware multiple times. It should be applied just once, otherwise the session data will be overwritten.

raphael's avatar

I'm facing exactly the same problem and have no solution for it.

Flash data is lost after redirecting.

My routes are properly set up, the web middleware appears only once.

Any other ideas?

imansyaefulloh's avatar

I'm facing the same problem,

here's my code

// controller
public function store(Request $request)
    {
        $this->validate($request, ['name' => 'required|unique:authors']);
        $author = Author::create($request->all());

        Session::flash("flash_notification", [
            "level"     => "success",
            "message"   => "Berhasil menyimpan $author->name"
        ]);

        return redirect()->route('admin.authors.index');
    }
// flash message
@if (session()->has('flash_notification.message'))
    <div class="container">
        <div class="alert alert-{{ session()->get('flash_notification.level') }}">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            {!! session()->get('flash_notification.message') !!}
        </div>
    </div>
@endif 
// route
Route::group(['middleware' => 'web'], function() {

    // ADMIN ROUTES
    Route::group(['prefix'=>'admin', 'middleware'=>['auth', 'role:admin']], function () {
        Route::resource('authors', 'AuthorsController');
    });

});
imansyaefulloh's avatar

I found the problem, its because the web middleware loaded twice like this

+--------+-----------+------------------------------+-----------------------+-----------------------------------------------------------------+--------------------+
| Domain | Method    | URI                          | Name                  | Action                                                          | Middleware         |
+--------+-----------+------------------------------+-----------------------+-----------------------------------------------------------------+--------------------+
|        | POST      | admin/authors                | admin.authors.store   | App\Http\Controllers\AuthorsController@store                    | web,web,role:admin |
|        | GET|HEAD  | admin/authors                | admin.authors.index   | App\Http\Controllers\AuthorsController@index                    | web,web,role:admin |
|        | GET|HEAD  | admin/authors/create         | admin.authors.create  | App\Http\Controllers\AuthorsController@create                   | web,web,role:admin |
|        | GET|HEAD  | admin/authors/{authors}      | admin.authors.show    | App\Http\Controllers\AuthorsController@show                     | web,web,role:admin |
|        | PUT|PATCH | admin/authors/{authors}      | admin.authors.update  | App\Http\Controllers\AuthorsController@update                   | web,web,role:admin |
|        | DELETE    | admin/authors/{authors}      | admin.authors.destroy | App\Http\Controllers\AuthorsController@destroy                  | web,web,role:admin |
|        | GET|HEAD  | admin/authors/{authors}/edit | admin.authors.edit    | App\Http\Controllers\AuthorsController@edit                     | web,web,role:admin |

so i changed my route from this

// route
Route::group(['middleware' => 'web'], function() {

    // ADMIN ROUTES
    Route::group(['prefix'=>'admin', 'middleware'=>['auth', 'role:admin']], function () {
        Route::resource('authors', 'AuthorsController');
    });

});

to this

Route::group(['prefix'=>'admin', 'middleware'=>['auth', 'role:admin']], function () {
        Route::resource('authors', 'AuthorsController');
});

I'm deleted web middleware group because now its loaded automatically, like it said on documentation https://laravel.com/docs/5.2/middleware#middleware-groups "Keep in mind, the web middleware group is automatically applied to your default routes.php file by the RouteServiceProvider."

and my routes list become

+--------+-----------+------------------------------+-----------------------+-----------------------------------------------------------------+---------------------+
| Domain | Method    | URI                          | Name                  | Action                                                          | Middleware          |
+--------+-----------+------------------------------+-----------------------+-----------------------------------------------------------------+---------------------+
|        | POST      | admin/authors                | admin.authors.store   | App\Http\Controllers\AuthorsController@store                    | web,auth,role:admin |
|        | GET|HEAD  | admin/authors                | admin.authors.index   | App\Http\Controllers\AuthorsController@index                    | web,auth,role:admin |
|        | GET|HEAD  | admin/authors/create         | admin.authors.create  | App\Http\Controllers\AuthorsController@create                   | web,auth,role:admin |
|        | GET|HEAD  | admin/authors/{authors}      | admin.authors.show    | App\Http\Controllers\AuthorsController@show                     | web,auth,role:admin |
|        | PUT|PATCH | admin/authors/{authors}      | admin.authors.update  | App\Http\Controllers\AuthorsController@update                   | web,auth,role:admin |
|        | DELETE    | admin/authors/{authors}      | admin.authors.destroy | App\Http\Controllers\AuthorsController@destroy                  | web,auth,role:admin |
|        | GET|HEAD  | admin/authors/{authors}/edit | admin.authors.edit    | App\Http\Controllers\AuthorsController@edit                     | web,auth,role:admin |

https://laravel.com/docs/5.2/middleware#middleware-groups

"Keep in mind, the web middleware group is automatically applied to your default routes.php file by the RouteServiceProvider."

Hope it helps.

6 likes
sameermalikrp's avatar
if you use  Route::resource dont use web middleware because its already in route::resource
screenager's avatar

As you all have noticed, there can be several reasons why flash messages may not show up in Laravel 5.2 or higher, but the deprecated 'web' middleware in your routes.php is probably the most mysterious one, as you don't really expect that it should be removed. This should be pointed in red on the official documentation. Thank you so much.

constb's avatar

My extra 2 cents: this may also be possibly caused by an older version of barryvdh/laravel-debugbar like one that installs when you're working on a L5.0-based project (my case). Debugbar generates extra requests that (in old versions) eat away reflashed data. If upgrading is not an option: \Debugbar::disable() in some handlers fixes the issue.

amitshrestha221's avatar

with() doesn't create session variable. It just prepares array to the view.

try


Session::flash('status','Message'); 

in controller

and



@if(Session::has('status')
{{ Session::get('status') }}
@endif


in view..

1 like

Please or to participate in this conversation.