Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

techhunt22's avatar

Return custom response on wrong http method usage in API

Hi everyone,

I’ve been exploring ways to handle errors caused by incorrect HTTP method usage. Currently, when a user makes an API request with the wrong HTTP method, Laravel returns its default error. I’d like to create a custom error response for such cases.

I came across some solutions, such as creating a middleware to handle this and passing the allowed routes as parameters. However, I feel there might be a better built-in way to achieve this in Laravel.

0 likes
1 reply
JussiMannisto's avatar
Level 50

Add custom exception rendering logic to bootstrap/app.php. The exception in this case is MethodNotAllowedHttpException:

use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

return Application::configure(basePath: dirname(__DIR__))
	...
	->withExceptions(function (Exceptions $exceptions) {
		$exceptions->render(function (MethodNotAllowedHttpException $e, Request $request) {
			if($request->expectsJson()) {
				return response()->json(['message' => 'Something'], status: 405);
			}
		});
	})

I included a check to see if a JSON response is expected. That way the default error page is rendered for non-API requests. You could also check if the requested path is relevant, e.g. $request->is('api/*').

https://laravel.com/docs/11.x/errors#rendering-exceptions

1 like

Please or to participate in this conversation.