Reputation: 221
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('/');
}
Upvotes: 1
Views: 5681
Reputation: 2632
Try using any
method in route and place your condition in controller then,
Route::any('calculate-cars', 'CarsController@calculateCars');
Hope this will work.
Upvotes: 0
Reputation: 26
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
Upvotes: 0
Reputation: 11636
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);
}
Upvotes: 0
Reputation: 5796
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.
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
Upvotes: 2
Reputation: 1929
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('/');
});
Upvotes: 8
Reputation: 9381
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');
Upvotes: 0