Crypcode
Crypcode

Reputation: 188

laravel MethodNotAllowedHttpException redirect to 404

I use laravel 8 tried to edit my exceptions\handler.php

public function render($request, Throwable $exception)
{
    if ($exception instanceof MethodNotAllowedHttpException) {
        abort(404);
    }
    
    return parent::render($request, $exception);
}

but his gives not 404 but 500 when checking routes where MethodNotAllowedHttpException

Upvotes: 1

Views: 981

Answers (2)

Ztuons Ch
Ztuons Ch

Reputation: 149

on Laravel 8 override default handler render function on App\Exceptions\Handler.php

public function render($request, Throwable $exception)
{
    if ($exception instanceof MethodNotAllowedHttpException) {
        if ($request->ajax() || $request->wantsJson() || $request->expectsJson()) {
            //405 for Method Not Allowed
            return response()->json(['error' => 'Bad Request'], 405);
        }
        else {
            return parent::render($request, $exception);
        }
    }
}

don't forget to add use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
to test in Postman set key=>Accept ,value => application/json to test handler
reff: Return a 404 when wrong ttp request type used(e.g. get instead of post) in laravel

Upvotes: 0

Howdy_McGee
Howdy_McGee

Reputation: 10643

One possible solution is to supply your routes/web.php file with a Route fallback. Try adding the following to the bottom of your web routes:

Route::fallback( function () {
    abort( 404 );
} );

Upvotes: 2

Related Questions