deadrabbits's avatar

Return JSON not found instead MethodNotAllowedHttpException when send POST method to not existing route

I want to return JSON not found instead of MethodNotAllowedHttpException when sending POST method to not existing route, how?

0 likes
4 replies
deadrabbits's avatar

@Tray2 Of course I have to use fallback routes. But it just works only if we use the GET method. when I try to use the POST method, MethodNotAllowedHttpException will be thrown up. CMIIW

Snapey's avatar

@deadrabbits more likely a page expired since an unknown route is unlikely to contain csrf and this is checked first.

gych's avatar

In app/Exceptions/Handler.php

Add this code in the render method, customize the returned message to your preferences

if ($e instanceof MethodNotAllowedHttpException && $request->isMethod('POST')) {
	return response()->json(['error' => 'Not found'], 404);
}

And don't forget to add this at the top in the Handler.php file

use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

Please or to participate in this conversation.