THE SITUATION:
Sorry in advance if it has already been asked. But no matter what I can never make it works.
I am using Laravel 5 as API.
I have a simple function to edit a task.
I am testing it through my web app or through Postman.
I am always getting this error:
TokenMismatchException in compiled.php line 3123:
THE CODE:
The function:
public function updateTask(Request $request)
{
$id = $request->input('id');
$task = Task::find($id);
$task->name = $request->input('name');
$task->type = $request->input('type');
$task->save();
return $task;
}
The route:
Route::group(['middleware' => ['web']], function () {
Route::post('update', 'TaskController@updateTask');
});
THE QUESTION:
Why I am getting that error?
I solved it by inserting the route name as an item in the array $except in the file:
Like this:
Try to add this in your form:
It works from your web app because your web app is passing the token.
You need to open up
app/Http/Kernel.php
and comment out\App\Http\Middleware\VerifyCsrfToken::class,
. However this will leave your site vulnerable to CSRF attacks so you should also find another way to protect your site.My suggestion would be to keep the CSRF middleware and create a new route group with a prefix of your choice ( usually something like
api/v1/
) which is outside theweb
middleware group. These routes would then not be protected by CSRF so you should find another way to protect them. I've recently had a lot of success doing this exact same thing withjwt-auth
. https://github.com/tymondesigns/jwt-authOf course, if your front end is not completely decoupled with your backend and Laravel is outputting the initial page which is then later controlled by angular, you can drop the CSRF token into a meta tag and grab it later with angular and pass it in the header
X-CSRF-TOKEN
, then Laravel will pick it up.You need to pass this in your headers;