Laravel 4 how to display flash message in view?

2019-03-10 22:10发布

I'm trying to get my flash message to display.

This is in my routing file

Route::post('users/groups/save', function(){

return Redirect::to('users/groups')->withInput()->with('success', 'Group Created Successfully.');

});

This is in my view

{{ $success = Session::get('success') }}
@if($success)
    <div class="alert-box success">
        <h2>{{ $success }}</h2>
    </div>
@endif

But nothing is working.

When I try this, I get an error Variable $success is undefined. But it actually shows the flash message too.

{{ Session::get('success') }}
@if($success)
    <div class="alert-box success">
        <h2>{{ $success }}</h2>
    </div>
@endif

11条回答
Juvenile、少年°
2楼-- · 2019-03-10 22:35

this should work at localhost and on host and i tried it.

<?php $success = Session::get('success'); ?>
@if($success)
    <div class="alert-box success">
        <h2>{{ $success }}</h2>
    </div>
@endif
查看更多
ゆ 、 Hurt°
3楼-- · 2019-03-10 22:36

when you set variable or message using ->with() it doesn't set the variable/message in the session flash, rather it creates an variable which is available in your view, so in your case just use $success instead of Session::get('success')

And in case you want to set the message in the session flash the use this Session::flash('key', 'value'); but remember with session flash the data is available only for next request.

Otherwise you can use Session::put('key', 'value'); to store in session

for more info read here

查看更多
霸刀☆藐视天下
4楼-- · 2019-03-10 22:38

I fixed mine by changing the session driver in config/session.php from array to file !

查看更多
小情绪 Triste *
5楼-- · 2019-03-10 22:39

This works for me

@if(Session::has('success'))
    <div class="alert-box success">
        <h2>{{ Session::get('success') }}</h2>
    </div>
@endif
查看更多
再贱就再见
6楼-- · 2019-03-10 22:45

This link describes how to do this http://vegibit.com/flash-messages-in-laravel/

Just tried with laravel 5 - works to me.

查看更多
男人必须洒脱
7楼-- · 2019-03-10 22:47

i just realized in using the Redirect::to(), when you use the withInput() method, chaining a with() function to pass variables will not work. the only way is either you flash your inputs separately using Input::flash(), and use the with() to pass your variables or you pass your variable via session using Session::flash('key','val') and retrieve in the view via session::get('key').

查看更多
登录 后发表回答