Search code examples
phplaravellaravel-5laravel-5.3laravel-5.4

Why if I don't put a {{csrf_field()}} at the end of a form (in a Laravel 5 view) I obtain a TokenMismatchException?


I am pretty new to PHP and Laravel and I have the following doubt about the {{csrf_field()}} notation inserted into a <form>.

Into a view I have the following form:

<form method="post" action="/registration">

  <div class="form-group">
    <label>Nome</label>
    <div class="input-group">
      <div class="input-group-addon"><i class="fa fa-user"></i></div>
      <input type="text" name="name" class="form-control" placeholder="Inserisci il tuo nome">
    </div>
  </div>

  <div class="form-group">
    <label>Cognome</label>
    <div class="input-group">
      <div class="input-group-addon"><i class="fa fa-user"></i></div>
      <input type="text" name="surname" class="form-control" placeholder="Inserisci il tuo cognome">
    </div>
  </div>

  <!-- Some other fields -->

  {{csrf_field()}}

  <button type="submit" class="btn btn-default">Submit</button>

</form>

That is handled by this minimialistic controller method:

public function store(Request $request)
{
    return $request->all();
}

So if I put the {{csrf_field()}} "statment" before the submit button it works fine and the request is correctly handled by the controller method but if I delete this line it can't works and I obtain a TokenMismatchException.

Why it is so and what exactly represent this {{csrf_field()}} and why have I to use it in a form?


Solution

  • CSRF stands for Cross-Site Request Forgery.

    In this case, Laravel is requiring this field to be sent with the request so that it can verify the request is not a forgery when posted back.

    A good explanation can be found here: https://stackoverflow.com/a/33829607/1068537