Why does the Laravel API return a 419 status code on POST and PUT methods?

Viewed 101338

I am trying to create a RESTful API by using Laravel. I have created my controller using php artisan make:controller RestController and this is my controller code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class RestController extends Controller
{
    private $arr = array(
            array("name"=>"jon", "family"=>"doe"),
            array("name"=>"jhon", "family" => "doue")
        );
    public function index(){
        return json_encode($this->arr);
    }

    public function store(Request $request){
        return "oops!!";
    }

    public function update (Request $request, $id){
        return "test";
    }

}

I have added this line of code to create this route in my routes/web.php file:

Route::resource('person', 'RestController');

When I try to test this api on GET /person it works fine but on POST and PUT I am getting a 419 status code from Laravel.

5 Answers

As per my Knowledge there are two methods to solve this

Method 1: Add CsrF Token

Method 2: Exclude URIs from CSRF protection

How to use

Method 1: Add one more variable to your POST request

_token: "{{ csrf_token() }}"

Example for Ajax

req = $.ajax({
    type: "POST",
    url: "/search",
    data: {
        "key": "value",
        _token: "{{ csrf_token() }}",
    },
    dataType: "text",
    success: function(msg) {
        // ...
    }
});

Example if you using forms

<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">

Method 2: There is a file named VerifyCsrfToken in following location

yourProjectDirectory/app/Http/Middleware

Add your URL in following method

 protected $except = [
     'url1/',
     'url2/',
 ];

When To use

  • If you are the owner(full control) of API, use Method 1, as CSRF Token adds security to your application.

  • If you are unable to add CSRF Token like in case if you are using any third party API's, webhooks etc., then go for Method 2.

This can solve by excluding csrf protection of specific route you want to.

Inside your middleware folder, edit the file called VerifyCsrfToken.php

protected $except = [
    'http://127.0.0.1:8000/person/'
];

I solved this problem by changing my server cache setting. You can disable all of your caching systems (Nginx, Cloudflare, ...) to check it and then turn it on by applying QueryString + Cookie to prevent caching a page with old csrf token in it.

I had the same issue when did POST requests to a Laravel API.

I solved the issue sending Accept: application/json in the headers request.

Related