TokenMismatchException in VerifyCsrfToken.php Laravel 5.2

I have got the dreaded VerifyCsrfToken error in my Laravel 5.2 project.

Relevant codes are below:

Route which is throwing the error

Route::group(['middleware' => ['web']], function(){
    Route::resource('register', 'RegisterController');
});

Error is thrown when I try to register a new user using POST request

Register Controller

public function store(Request $request)
{
    return AppUser::create([
        'name' => $request->input('name'),
        'email' => $request->input('name'),
        'contact_number' => $request->input('contact_number'),
        'api_token' => str_random(60),
        'password' => $request->input('password'),
    ]);
}

Expected Output
{
  "email": "test.name",
  "contact_number": "654987123",
  "updated_at": "2016-10-06 06:30:26",
  "created_at": "2016-10-06 06:30:26",
  "id": 4
}

What makes my question different from the other VerifyCsrf mismatch questions are, I don’t have a form to add a {{ csrf_token() }} hidden field. I just sent the request using Postman (and curl) and the user needs to be registered.

When I do the following edit on app/Http/Middleware/VerifyCsrfToken.php

protected $except = [
    '/*'
    //
];

The error disappears and it works as it should, but I don’t think is the recommended way.

Thanks

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Store the token in the root blade file. if you are using only default view, then may be in layout/main.blade.php

<meta name="csrf-token" content="{{ csrf_token() }}">

If using jQuery, you can now instruct it to include the token in all request headers.
 $.ajaxSetup({
     headers: {
           'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
       }
   });

If you still get errors follow: https://gist.github.com/ethanstenis/3cc78c1d097680ac7ef0


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x