humpdi February 2016

Laravel: how to prevent a MethodNotAllowedHttpException in RouteCollection.php when someone access a post-route without giving post parameters?

Laravel: how to prevent a MethodNotAllowedHttpException in RouteCollection.php when someone access a post-route without giving post parameters?

When i define a post route its only accessable by a post request. If i call the url normaly in a browser, it throws an exception. how to prevent this?

Answers


noodles_ftw February 2016

Anyone can do a request to any of your routes using a method that isn't allowed. You can make a view for the exception in the resources/views/errors folder. Laravel comes with an error page for the HTTP status code 503 (Service Unavailable Error) by default.

The HTTP status code for the MethodNotAllowedHttpException is 405, so making a view called 405.blade.php will cause Laravel to present that view instead of the MethodNotAllowedHttpException message.


Froxz February 2016

This should do the job This will catch all errors like, MethodNotAllowed or 404(page not found) or ModelNotFound or TokenMissMatch and redirect to any route you desire with proper error!

Handler.php

    public function render($request, Exception $e){
       if ($e instanceof ForbiddenException) {
            return redirect()->route('name')->withErrors(['error' => $e->getMessage()]);
       }
       return parent::render($request, $e);
    }

Or just for Method not allowed

use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
    if ($e instanceof MethodNotAllowedHttpException) {
        return redirect()->route('name')->withErrors(['error' => $e->getMessage()]);
    }


Ralph John Galindo February 2016

Use Route::any() or Route::match()

Example:

Route::match(['get', 'post'], '/', function () {
    //
});

Route::any('foo', function () {
    //
});


Eduardo Chongkan February 2016

I tried the match and any methods but they were not what I needed.

This is what I did:

1- Added the default error handler in the Base controller. 2- Called the error manually for each forbidden HTTP METHOD.

enter image description here

Then, on the BaseController:

enter image description here

Post Status

Asked in February 2016
Viewed 3,392 times
Voted 11
Answered 4 times

Search




Leave an answer