Search code examples
phplaravel-5csrflaravelcollective

TokenMismatchException when resubmitting a form


I am using Laravel 5.3 and the laravelcollective/html form helpers.

When I submit a form, if the validation fails it takes you back to the same form using return redirect()->back()->with

Then if I resubmit the same form again I will get a TokenMismatchException, what happenned is that the csrf token did not refreshed after the form was reloaded.

Any ideas of how can I get the token refreshed?

Update 11/07

To open the form I use the following:

{!! Form::open(['url'=>'/user/create', 'method'=>'post', 'id'=>'create']) !!}

Which automatically adds the token field.

But Also I have tried adding the token manually, like this:

{!! Form::open(['url'=>'/user/create', 'method'=>'post', 'id'=>'create']) !!}
{!! Form::token() !!}

Here the token is actually created twice, both tokens are be the same.


Solution

  • The problem was that I was sending the value _token back to the view. What I was doing was:

    return redirect()
    ->back()
    ->with(
    ['errors' => $validator->errors()->all()] 
    + $request->input()
    );
    

    Where the $request->input('_token') was not being filtered. Instead I have changed it for the following which works, as it does filter _token:

    return redirect()
    ->back()
    ->withErrors($validator->errors()->all())
    ->withInput($request->input());