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/*').