Im testing my laravel rest API with postman, my end point only allow POST method but when i test it with GET method the body return webpage instead of json. How could i handle the response to return json although the response is 405?
Asked
Active
Viewed 2,246 times
0

Ferry Sanjaya
- 224
- 2
- 17
1 Answers
4
You can handle it in function render
of app/Exceptions/Handler.php
Ex:
public function render($request, Exception $e)
{
if ($e instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException) {
return response()->json(['message' => $e->getMessage(), 405);
}
return parent::render($request, $e);
}
The docs for it: https://laravel.com/docs/5.8/errors#render-method
I think Laravel has the response as JSON for it by default. You also can add to headers of request.
Content-Type: application/json
Accept: application/json

Sang Nguyen
- 1,702
- 15
- 16
-
1$e->getMessage() return empty string – Ferry Sanjaya Nov 13 '19 at 06:21
-
1You can use your custom message. `return response()->json(['message' => 'Method is not allowed!', 405);` – Sang Nguyen Nov 14 '19 at 07:03