Search code examples
laravellaravel-5laravel-routinglaravel-request

Laravel restful api error 500 (store and destroy)


I am new to restful api, and I met a problem: when I request destroy with delete method and store with post method, both will return 500 error. But I use get method to request index and show, both are ok. What is the problem?

Here is my code and request:

delete http://***.com/RestfulPrac/public/customers/10000001

get   http://***.com/RestfulPrac/public/customers/10000001

post http://***.com/RestfulPrac/public/customers
 class CustomersController extends Controller
 {
    public function index(){

    $customersInfo = customers::all();
    return $customersInfo;

    }

    public function show($cust_id){

    $customer = customers::where('cust_id',$cust_id)->first();
    return $customer;
    }
    public function store()
    {
    
    echo "store";
    }

   public function destroy()
   {

      return "success";
   }
}
Route::resource('customers','CustomersController');

The apache access.log:

"DELETE /RestfulPrac/public/customers/1000000001 HTTP/1.0" 500 20246 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"

The apache error.log:

[Thu Jun 02 09:09:24.324782 2016] [negotiation:error] [pid 4328:tid 1676] [client 127.0.0.1:4940] AH00690: no acceptable variant: D:/XAMPP/apache/error/HTTP_NOT_FOUND.html.var

The laravel.log:

local.ERROR: exception 'Illuminate\Session\TokenMismatchException' in F:\PhpstormProjects\RestfulPrac\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:67
Stack trace:

Solution

  • Based on the Laravel error log you have a csrf token mismatch. If you are building an API you probably will not want to use the 'web' middleware. That middleware group is starting a session and will check for a csrf token on all requests that aren't using READ (GET, HEAD, OPTIONS) HTTP methods.

    By default Laravel is putting all your routes in routes.php in a route group with the 'web' middleware applied (If on version >= 5.2.27) when it loads them in your RouteServiceProvider in app\Providers.

    That would probably be where to start, based on the Laravel error log.

    This may be of some help: VerifyCsrfToken always called when route to API Middleware Laravel 5.2.35