欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

laravel 移除 删除 remove session flash session::flash

Laravel Session Flash persists for 2 requests

Recently I have changed to Laravel from Codeigniter, everything was going fine except I encountered a problem with Session::flash.

when I create new user I get success message but It will persist for 2 requests, even I didn't pass the validator: enter image description here

my code in UsersController:

function getCreateUser(){
    $config = array(
        'pageName' => 'createUser',
        'pageTitle' => 'Create User',
        'formUrl'   => action('UsersController@postCreateUser'),
        'modelFields'   => array(
            array('db_name' => 'employee_id', 'text' => 'Employee Id', 'mandatory' => TRUE),
            array('db_name' => 'full_name', 'text' => 'Full Name', 'mandatory' => TRUE),
            array('db_name' => 'email', 'text' => 'Email', 'mandatory' => FALSE),
            array('db_name' => 'password', 'text' => 'Password','value' => '12345', 'mandatory' => TRUE)
            ),
        'submit_text' => 'Create'
        );
    return View::make('layouts.form', $config);
}

function postCreateUser(){
    $config = array(
        'pageName' => 'createUser',
        'pageTitle' => 'Create User',
        'formUrl'   => action('UsersController@postCreateUser'),
        'modelFields'   => array(
            array('db_name' => 'employee_id', 'text' => 'Employee Id', 'mandatory' => TRUE),
            array('db_name' => 'full_name', 'text' => 'Full Name', 'mandatory' => TRUE),
            array('db_name' => 'email', 'text' => 'Email', 'mandatory' => FALSE),
            array('db_name' => 'password', 'text' => 'Password','value' => '12345', 'mandatory' => TRUE)
            ),
        'submit_text' => 'Create'
        );
    $validator = User::validate(Input::all());
    if($validator->passes()){
        $user = new User(Input::all());
        $user->password = Hash::make(Input::get('password'));
        $user->Company_id = '1';
        $user->save();

        Session::flash('message', 'User Created Successfully!'); 
        Session::flash('alert-class', 'alert-success');
        return View::make('layouts.form', $config);
    } 

    return View::make('layouts.form', $config)->withErrors($validator->messages());
}

in form.blade:

@if ( $errors->count() > 0 )
<div class="alert alert-danger">
    <p>The following errors have occurred:</p>

    <ul>
        @foreach( $errors->all() as $message )
        <li>{{ $message }}</li>
        @endforeach
    </ul>
</div>
@endif

in master.blade:

@if(Session::has('message'))
<p class="alert {{ Session::get('alert-class', 'alert-info') }} alert-dismissable"> {{ Session::get('message') }}</p>
@endif

Maybe I'm not alone with this issue, here is another unanswered question.

Update

For anyone in future facing this problem: Never flash session data without redirecting.

My code now looks like this:

function postCreateUser(){
    $validator = User::validate(Input::all());
    if($validator->passes()){
        $user = new User(Input::all());
        $user->password = Hash::make(Input::get('password'));
        $user->Company_id = '1';
        $user->save();

        Session::flash('message', 'User Created Successfully!'); 
        Session::flash('alert-class', 'alert-success');
    } else {
        Session::flash('message', Helpers::formatErrors($validator->messages()->all()));
        Session::flash('alert-class', 'alert-danger');
    }

    return Redirect::action('UsersController@getCreateUser');
}
shareimprove this questionedited May 23 '17 at 12:02Community♦11asked Jul 4 '14 at 18:51Mohammad Walid1,9551136

5 Answers 正确答案

You are Flashing session data and creating a view instead of redirecting, meaning the message will Flash for this request and for the next one, showing twice.

If you want to show the message on the current request without redirecting, I would suggest providing the errors to your View::make instead of trying to Flash the messages. If you MUST Flash the message on the current request, then you will need to Session::forget('key') or Session::flush() after your view.

shareimprove this answeredited Feb 3 '16 at 16:39answered Jul 4 '14 at 19:07Drew34525

   Thanks for your clarification, I have solved the problem after your answer. – Mohammad Walid Jul 4 '14 at 19:31   I could not get flash message. Let me know what's an exact issue. – 2plus Aug 6 '14 at 6:272 @Drew: Session::flush('key') is not a valid function call, flush() does not take any argument, instead it deletes all session data, can you please update your answer? Session::forget('key') can be used to delete any session data, I suggest :) – user2432443 Jun 17 '15 at 12:08

As @Drew said earlier

You are Flashing session data and creating a view instead of redirecting, meaning the message will Flash for this request and for the next one, showing twice.

An easy way to flash a message once when you are creating a view is:

Session::flash($key, $value);
Session::push('flash.old', $key);

Happy coding!

shareimprove this answeranswered Jul 31 '15 at 10:22TechyTimo2,29453243

1 For anyone else sort of confused by this like I was, if you are flashing like this: Flash::warning('warning text'); then what you want to follow up with is Session::push('flash.old', 'flash_notification.message'); and Session::push('flash.old', 'flash_notification.level');. This will make it only display on the first page load. You can dd($request->session()); to see how the session stores these values if you want. – Brynn Bateman Jan 14 '16 at 18:31    worked great for me, thanks! – the_web May 29 '16 at 14:27

I had a similar problem, but I couldn't use Return::redirct, as I was using Ajax to to post to and from a within a set of Tabs.

Therefore, I was calling

Input::flashExcept('_token');

only if the validation failed and returning a view with the old input. Assuming validation passed and I wanted to run some functions and create a new view based on new data, I would call:

Session::forget('_old_input');

I would put this before my final View::make

Hope this helps (or makes sense)...

shareimprove this answeranswered Feb 1 '15 at 20:32Neil Telford162

The following seems to be available from version 5.1 onward. Although the method is notmentioned on Laravel's documentation page about sessions.

session()->now()

This is the same as flash, except it won't persist to the next request.

shareimprove this answeredited Nov 15 '17 at 16:11answered Nov 15 '17 at 16:05aross1,60711830

A good method to repopulate form with old data:

Controller:

View::make( 'view.name' )->withOldFormData( Input::all() );

View:

{{ Form::model( $old_form_data ) }}
shareimprove this answeranswered Dec 7 '15 at 22:40AMIB1,1661016

3 How does this answer apply to the question? – Kalagen Nov 7 '16 at 1:39   This is an alternate method to solve the problem. Instead of redirecting to a new route, he can populate form with this safe method ! – AMIB Dec 10 '16 at 2:41 

来自  https://stackoverflow.com/questions/24579580/laravel-session-flash-persists-for-2-requests

普通分类: