Laravel 5 - How do I handle MethodNotAllowedHttpException

13,465

Solution 1

// Exceptions/Handler.php

use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

public function render($request, \Exception $e)
{
    if ($e instanceof MethodNotAllowedHttpException) {
        // …
    }

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

Solution 2

In Laravel 5.4, I did it like this:

File location: app/Exceptions/Handler.php

Add this code at the top of the file:

use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

And modify the method code as belows:

/**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof MethodNotAllowedHttpException) 
        {
            return response()->json( [
                                        'success' => 0,
                                        'message' => 'Method is not allowed for the requested route',
                                    ], 405 );
        }

        return parent::render($request, $exception);
    }
Share:
13,465
Salal Aslam
Author by

Salal Aslam

-

Updated on June 15, 2022

Comments

  • Salal Aslam
    Salal Aslam almost 2 years

    Where can I catch a MethodNotAllowedHttpException in Laravel 5+?

    In Laravel 4 I was able to do this in start/global.php.

  • Frédéric Klee
    Frédéric Klee almost 7 years
    If you have a problem using codeinstanceofcode with php 7.1 you can use codeis_a()code. If someone has a explanation why I didn't get codetruecode with codeinstanceofcode ? Thanks.