Return a 404 when wrong ttp request type used(e.g. get instead of post) in laravel

laravel throw exception
laravel catch (exception in controller)
laravel throw exception with message
laravel return error response
laravel error handling best practices
laravel custom error page
laravel api exception handling
http status codes

I am developing a rest API and sometimes the frontend call an endpoint with the wrong HTTP request type. For example, I have a route (/users/unassigned) and the type of the route is "GET". Imagin my frontend call this route with a "POST" request. the following error occurs. The POST method is not supported for this route. Supported methods: GET, HEAD, PUT, DELETE. What I want is that the API response a JSON in these situations and I can handle the exception.I have used the Route::fallback but this method catch every exception of the routes. I need a function that only handles the told problem.

you can make some adjustment in your exception handler.

in app/Exceptions/Handler.php file's render function

public function render($request, Exception $exception)
{
    if ($exception instanceof MethodNotAllowedHttpException) {
        if ($request->ajax()) {
            return response()->json(['error' => 'Route Not Found'], 404);
        }
        else {
            //something else
        }
    }

    return parent::render($request, $exception);
}

and add use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; at the top use section.

Error Handling - Laravel, This class contains two methods: report and render . We'll examine each of these methods in detail. The report method is used to log exceptions or send them to� To expand on MainMa's example: If a log lookup tool spit out text files (e.g., a thin wrapper around log files that just spits out the log file as-is), a 204 would be appropriate for an empty log file. If the response was an empty JSON object (e.g., {content: ''}), a 204 response would be inappropriate. – Brian Jun 22 '16 at 14:41

One way is to handle it with app/Exceptions/Handler.php:

public function render($request, Exception $e)
{
    if ($request->ajax() || $request->wantsJson()) {
        return response()->json([
            'error' => $e->getMessage(),
        ], 400);
    }

    return parent::render($request, $e);
}

This will ouput the error message as json for all exceptions when the request is made by ajax or the request expect json.

You can also add a check for type of exception like this:

if ($exception instanceof MethodNotAllowedHttpException) {
    // Code...
}

HTTP Status Codes, HTTP defines 40 standard status codes that can be used to convey the to GET, regardless of the type employed in the original request (e.g., POST). Instead, the client may send a GET request to the value of the 400 (Bad Request) The 404 error status code indicates that the REST API can't map the� If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead .

change in your Handler.php

like

protected $dontReport = [
             \Illuminate\Auth\AuthenticationException::class,
            \Illuminate\Auth\Access\AuthorizationException::class,
            \Symfony\Component\HttpKernel\Exception\HttpException::class,
            \Illuminate\Database\Eloquent\ModelNotFoundException::class,
            \Illuminate\Session\TokenMismatchException::class,
            \Illuminate\Validation\ValidationException::class,
            //
];

protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
         $arr = array("status" => 400, "message" =>"Unauthorized access", "data" => array());
             return \Response::json($arr);
        }
        return redirect()->guest('login');
    } 

404 Not Found Error: What It Is and How to Fix It, All HTTP response status codes that are in the 4xx category are considered client error responses . These types of messages contrast with errors� Open the .htaccess file (or create one if needed) in the root directory, enter this in 'ErrorDocument 404 /404.html' and save the change. The error page will be generated with this code. The error page will be generated with this code.

Check what type of request you are getting in your $request variable, then handle it with condition.

Protect Against Malicious POST Requests, POST requests are sort of the opposite of GET requests. Instead of getting some resource or file from the server, data is being posted or sent to it. Type of request (e.g., GET , POST , HEAD , etc.) a POST request to a URL that is not equipped to handle it, the server may return a 404 “Not Found” response. Many web browsers implemented this code in a manner that violated this standard, changing the request type of the new request to GET, regardless of the type employed in the original request (e.g., POST). RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request.

Thank you so much. I use the following code in my handler.php.

    {
        if ($this->isHttpException($exception)) {
            switch ($exception->getStatusCode()) {

                // not authorized
                case '403':
                    return Response()->json(["error" => "not authorized."],403);
                    break;

                // not found
                case '404':
                    return Response()->json(["error" => "Route not found."],404);
                    break;

                // internal error
                case '500':
                    return Response()->json(["error" => "internal error."],500);
                    break;

                case '405':
                    return Response()->json(["error" => "request type not match."],405);
                    break;

                default:
                    return $this->renderHttpException($exception);
                    break;
            }
        }
        else {
            return parent::render($request, $exception);
        }
    }

The main point is http code 405 for not allowed methodes. special thanks to @apokryfos.

Search REST API | API Reference, HTTP Verb: GET Required API Key: any key with the search ACL. Description: You can also query an index with a GET request. The GET method's URL varies� Change the DNS servers used by your computer, but usually only if an entire website is giving you a 404 error, especially if the website is available to those on other networks (e.g., your mobile phone network or a friend in another city).

http_response_code - Manual, http_response_code — Get or Set the HTTP response code Both of these values will default to a 200 status code if used in a web server environment. POST, for example, is usually deactivated for HTML pages, while the method functions in PHP documents. If you change the extension type, for example, from index.html to index.php, there’s a good chance that you’ll have solved the “405 Method Not Allowed” problem.

Learn how to customise API error messages with Laravel 5+, Learn how to secure and customise your Laravel API with custom This returns HTML instead of JSON, not ideal when using an API E.g. /api/cars/44556 a restricted endpoint or tried to issue an GET request on a PATCH etc all bad endpoints and return the response as JSON and the HTTP error� You can change your custom post type slug which is done by altering the rewrite parameter when registering your custom post type; 3. Auto Flush Rewrite Rules (for developers) Another cause of 404 errors is whenever a new post type is registered you have to “flush” your rewrite rules in WordPress.

The Guzzle HTTP client — Guzzle documentation, Guzzle gives PHP developers complete control over HTTP requests while Set to true to use the Guzzle bundled SSL certificate bundle (this is used by Each request method of the static client (e.g. get(), post()`, ``put(), etc) accepts disable throwing exceptions for unsuccessful HTTP response codes (e.g. 404, 500, etc). If you find the post has answered your issue, then please mark post as 'answered'.

Comments
  • Use the handler. App\Exceptions\Handler::class, In your case even if the response is not JSON? the response code is clear: 404
  • You get a 405 error in these cases. That should be enough to handle the response. The content should not matter.
  • mark as helpful if you get proper your answer. thank you.