1
votes

I do a post request to a route calculate-cars and display an other view with some data I query based on the data I entered in the form I do the post request from, but I want to redirect to the homepage when someone access this route directly.

Unfortunately I keep getting this error:

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException No message

my route:

Route::post('calculate-cars', 'CarsController@calculateCars');

I know I get this error because I access a post route directly but I try this in my controller method but I still get the same error:

if (!$request->isMethod('post')) {
    return redirect()->to('/');
}
6

6 Answers

6
votes

Add another route

Route::get('calculate-cars', function () {
    return redirect()->to('/');
});

If you'r using Laravel 5.5, you can do it like this:

Route::redirect('/calculate-cars', '/', 301);

UPDATE: The method Route::redirect will redirect the post route as well, it's not useful in your case.

Just put this in your routes/web.php file:

Route::get('calculate-cars', function () {
    return redirect()->to('/');
});
2
votes

You didn't explain why you expect a POST request. Do you save calculations to save time (cache)? Only in that case, POST is a right decision.

In addition to others: it's important to choose your http methods wisely.

  • GET: for READ (no system change)!
  • POST: for CREATE
  • etc.

Like I said, why did you choose for POST? Change only to GET if you want to read. MDN has a clear summary about the methods: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

0
votes

but I want to redirect to the homepage when someone access this route directly.

That means when a user does a GET

Your route Route::post('calculate-cars', 'CarsController@calculateCars');

only allows POST

So change it to

Route::any('calculate-cars', 'CarsController@calculateCars');

0
votes

I understand you are trying to redirect the user upon MethodNotAllowedHttpException

You can use Laravel's Exception Handler for this:

Open app/Exception/Handler.php and change render method to this:

public function render($request, Exception $exception)
{
    if ($exception instanceof ModelNotFoundException)
    {
        return \Redirect::to('/');
    }
    return parent::render($request, $exception);
}
0
votes

Rename your route to something different and test it again.

For instance

Route::post('calculate-cars', 'CarsController@calculateCars');

could be like

Route::post('calculate-test-cars', 'CarsController@calculateCars');

I have had cases where changing the route might do the trick. Not sure if it's always like that.

Let me know

0
votes

Try using any method in route and place your condition in controller then,

Route::any('calculate-cars', 'CarsController@calculateCars');

Hope this will work.