5
votes

Is there a way to check route fallback for post methods? This code works for any get url in my routes file i.e. I get this response("Page Not Found.") if I type and wrong GET url.

Is there a way to check the same for POST urls?

Route::fallback(function(){
    return response()->json([
        'status'    => false,
        'message'   => 'Page Not Found.',
    ], 404);
});
5

5 Answers

5
votes

Define custom fallback route at end of your routes/api.php

Route::any('{any}', function(){
    return response()->json([
        'status'    => false,
        'message'   => 'Page Not Found.',
    ], 404);
})->where('any', '.*');
4
votes
use Request;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

In app/Exceptions/Handler.php replace render function

public function render($request, Exception $exception)
    {
        if (Request::isMethod('post') && $exception instanceof MethodNotAllowedHttpException) {
            return response()->json([
                'message' => 'Page Not Found',
                'status' => false
                ], 500
            );
        }
        return parent::render($request, $exception);
    }

Or if you want both NotFound And MethodNotAllowed then

public function render($request, Exception $exception)
    {
        if ((Request::isMethod('post') && $exception instanceof MethodNotAllowedHttpException) || (Request::isMethod('post') && $exception instanceof NotFoundHttpException)) {
            return response()->json([
                'message' => 'Page Not Found',
                'status' => false
                ], 500
            );
        }
        return parent::render($request, $exception);
    }
3
votes

Put this script end of your routes file.

Route::any('{url?}/{sub_url?}', function(){
    return response()->json([
        'status'    => false,
        'message'   => 'Page Not Found.',
    ], 404);
})

It will automatically detect if someone try to hit any other routes like below.

laravel_project_path/public/any_string
laravel_project_path/public/any_string/any_string
0
votes

Try: In Route API

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

In resources folder

Follow:

  1. Go to resources
  2. Go to views
  3. Create errors folder
  4. Create blade 500.blade.php
-1
votes

You can use given method to check POST urls.

Route::fallback(function(){
    return \Response::view('errors.404');
});