Search code examples
phplaravelcsrf

Laravel 5 CSRF global token hidden field for all forms in a page


I recently migrated to Laravel 5, and now CSRF check is on every post submission. I thought about removing it but I want to follow the best practices, so I'll keep it that way.

On the other hand, I'm problems submitting ajax requests.. my page has multiple forms and some submissions are not even from forms, just plain ajax calls. My idea is to have one single hidden "token" input on the page and attach it to every submission. Are there any drawbacks on having that universal single token input?

Also, how can I output the token? Would it be ok to just create a hidden input on the page footer?


Solution

  • I don't see any drawbacks. You can easily create a global token field in your layout file:

    <input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />
    

    Or if you use the form builder:

    {!! Form::token() !!}
    

    In jQuery you could use something like this to attach the token to every request.