So when a user randomly types a URL on a route that exists, they get an error message:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.
After doing some searching, all the posts I can find suggest to change the render function inside of App\Exceptions\Handler and change it to this:
public function render($request, Exception $exception)
{
if($exception instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException){
return abort('404');
}
return parent::render($request, $exception);
}
However, with the newer version of Laravel this no longer exists. One post mentioned to add this in routes\web.php:
Route::fallback( function () {
abort( 404 );
} );
This works fine but I'm not sure if this is the best approach/right place to have it? Is there are any other alternative way?
I have also attempted to change the register function inside of App\Exceptions\Handler to this per the Laravel Doc (https://laravel.com/docs/9.x/errors#rendering-exceptions):
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => 'Record not found.'
], 404);
}
});
}
but it does not work
CodePudding user response:
In a newer version on Laravel, you can add
$this->renderable(function (Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException $e) {
// do something
});
this line inside a register
method on a class \App\Exceptions\Handler
If you want to handle NotFoundException you should use
$this->renderable(function (Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e) {
// do something
});
You can find more detailed answer on Laravel documentation here: https://laravel.com/docs/9.x/errors#rendering-exceptions