skip to Main Content

I have a POST method in my route

Route::post('blog/{id}', 'AppHttpControllersBlogController@sendGrade');

And when I also specify POST in the request, then everything is fine

$.ajax({
  type: 'POST',

But when the request is GET, I will get an error

The GET method is not supported for this route. Supported methods: POST.

This is all obvious, but is it possible to avoid this so that if there is a GET method in the request, then instead of this error I would get a 404 error?

As far as I understand it can be done in the controller. Right now I have something like this when the entry doesn’t exist

if(!$blog){
  return abort(404);
}

Is it possible to do the same for the GET method?

2

Answers


  1. Route::match(['get', 'post'], 'blog/{id}', 'AppHttpControllersBlogController@sendGrade');
    
    /**
     * @throws NotFoundHttpException
     */
    public function sendGrade(string $id, Request $request): Response
    {
        if ($request->getMethod() === 'GET') {
            throw new SymfonyComponentHttpKernelExceptionNotFoundHttpException();
        }
     
        // code
    }
    

    in the exceptions/handler.php

    protected $dontReport = [
        NotFoundHttpException::class
    ];
    
    /**
     * @inheritDoc
     */
    public function render($request, Throwable $e)
    {
        if ($e instanceof NotFoundHttpException) {
            try {
                /** @var Client $guzzleClient */
                $guzzleClient = resolve(Client::class); // register the Client in appServiceProviders.php as singleton for example
                $result = $guzzleClient->get('/getNotFoundEndpoint');
                $body = $result->getBody()->getContents();
            } catch (Throwable $e) {
            }
    
            return response($body ?? '', 404);
        }
    
        return parent::render($request, $e);
    }
    
    Login or Signup to reply.
  2. add this route to your web.php file

    Route::get('blog/{id}', function () {
                abort(404);
     });
    

    this will work 100%

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search