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);
});
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', '.*');
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With