0

I created a route for buy an item in laravel 5.7

Route::post('/buy/item', "userController@buy_item")->name('buy_item_form');

Everything works fine but when I refresh the page(replace to GET Request) I got an MethodNotAllowedHttpException. The GET route not exist, Its must return an 404 error. I dont understant why its return me this exception.

1 Answer 1

2

You are using a post, with post you have a @csrf token. when you click on refresh, you are doing a GET method instead of a post and for hence you get the method not allow exception. If you are not sending data you can change it to a get [Route::get] method.

If you want to accept the 2 methods [post,get] to have a better experience and manage the possible errors. You can accept the 2 methods on the route like:

Route::match(array('GET','POST'),'/buy/item', 'userController@buy_item')->name('buy_item_form');

And on the controller, define what to do base on the method.

if (Request::isMethod('get')){
    // redirect user
}

if (Request::isMethod('post')){
    // do logic for post method
}

Sign up to request clarification or add additional context in comments.

13 Comments

I didn't create a GET route. so why I got an exception on GET request if the route not exist. This should return me an 404 error.
when you refresh or go to a page is a get method, if you submit data and set the method on the form to post, it will post the info instead of get. w3schools.com/tags/ref_httpmethods.asp
I mean that I created a Post Route And When I write the url of the post route on the url adress bar in my browser(Make a get Request) its return an exception and not 404 error. I can make a get route thet do abort(404) but is not must be happen anyway?
add this to your code, and you will see that you are doing a get on refresh Route::get('/buy/item', function(){ return "Get Request"; });
I can make this: Route::get('/buy/item', function(){return abort(404)}); But my question is why is not happend automaticly.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.