Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Route fallback for POST methods in Laravel?

Tags:

laravel

routes

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);
});
like image 610
azm_shah Avatar asked Apr 02 '19 07:04

azm_shah


3 Answers

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', '.*');
like image 160
Meow Kim Avatar answered Oct 13 '22 00:10

Meow Kim


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);
    }
like image 37
Akash Kumar Verma Avatar answered Oct 12 '22 23:10

Akash Kumar Verma


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
like image 40
narayansharma91 Avatar answered Oct 12 '22 23:10

narayansharma91