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('/');
}
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('/');
});
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
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');
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);
}
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
Try using any method in route and place your condition in controller then,
Route::any('calculate-cars', 'CarsController#calculateCars');
Hope this will work.
Related
If we just create a 404.blade.php page in resources/views/error it will work fine, but Auth() won't work on 404 page, to solve that if we follow the solution available on stackoverflow the Laravel auth errors will stop working. I use the following solution to do the work.
Create custom view
resources/views/errors/404.blade.php
in route.php
Route::any('{catchall}', 'PageController#notfound')->where('catchall', '.*');
create PageController and add this function
public function notfound()
{
return view('errors.404');
}
For Laravel 5.6 and later, you can use fallback in your routes\web.php:
Route::fallback('MyController#show404');
It works as an "catch all"-route.
See docs here.
Write below code in your Exceptions/Handler.php
if($this->isHttpException($exception)){
if(view()->exists('errors.'.$exception->getStatusCode())){
$code = array('status'=>$exception->getStatusCode());
return response()->view('errors.404',compact('code'));
}
}
Now create a new file in your view i.e errors/404;
Now in code array you can pass dynamic values
Not sure if this will help. Laravel has a PHP artisan command to publish error pages. Laravel Custom HTTP Error Pages
After you run this artisan command use Route:fallback() method as #KFoobar suggested. If you use a closure function, no need to use a controller. Make sure to add the below route at the ends of your routes file.
//Fallback/Catchall Route
Route::fallback(function () {
return view('errors.layout');
});
Shameless plug for my BLOG
I have Laravel app with Vue on front end, and Vue calls update method from controller using PUT request.
Request works, model gets updated, but I have issue with redirecting as it is redirecting also as a PUT instead of simple GET?
public function update(MomentsValidationRequest $request, Project $project, Task $task, Moment $moment)
{
foreach($request->materials as $material){
$material_id_array[$material['id']] = ['quantity' => $material['quantity']];
}
$moment->update($request->all());
if(isset($material_id_array))
$moment->materials()->sync($material_id_array);
return redirect()->back()->with(['alert-type' => 'success', 'message' => 'Moment updated!']);
}
So naturally, I am getting a method not allowed exception because it is redirecting to a route which is supposed to get a previous view only.
Route itself is fine, request method isn't.
For non-believers :)
Also a route:
I know this is a bit late. But incase anyone stumbles across this.
You state that you're using Vue in the front end. This would suggest that the put request is being made through an axios call.
I can't see this call, so this is only an assumption. But I believe the solution would be to return a json object instead of a response in the controller, and then redirect trigger a redirect from the Vue component itself.
In the controller:
Session::flash('alert-type', 'success');
Session::flash('message', 'Moment updated!');
return response()->json(true);
In the component:
axios.post('/moments', this.moment).then(() => {
window.location.replace("moments");
});
I believe this is something to do with how axios handles patch requests, it seems to attempt to handle a redirect response automatically, I could be wrong though, so any reply is welcome to if there's a better explanation.
You can use:
redirect()->back(303)->with(...)
No, redirection is made always with GET but you don't have such route defined. So you should create GET route that will do something with this.
It's possible only to redirect to GET routes.
I got this error-->'NotFoundHttpException in RouteCollection.php line 161'..When i try to call my additional controller in laravel 5.2..Already I did php artisan serve to activate localhost:8000..can you please explain the basic layout of routing with controller in laravel?
NotFoundHttpException occurs when no given route is matched to your given request to a certain endpoint/url.
Make sure you are sending the request to the correct url which is correctly defined in your routes.php (web.php for laravel 5.3+) with it's correct verb, (GET, POST, PATCH, etc).
Basic flow goes like this:
In your routes.php, you'd define a route like:
Route::get("/users", "UsersController#show");
then in your Http folder define that given controller with it's name which you referred in above call and anything proceeding # symbol is a callback function which gets called automatically.
So in your http/UsersController.php, you'd have:
public function show(Request $request) {
//Do something with your request.
return "Something"; //could be an array or string or
//whatever since laravel automatically casts it into JSON,
//but it's strongly recommended to use transformers and compact method.
}
For more information try looking at laravel docs, they provide an amazing way to get started tutorial. Laravel Docs
I'm using laravel 5 and this is my problem. User fill in form X and if he isin't logged in, he gets redirected to fill in more fields form OR he gets possibility to log in. Everything works just fine, if user fill in additional fields, but if he login, laravel redirects user to form X with GET method instead of POST.
This is how my middleware redirect looks like:
return redirect()->guest('user/additional-fields');
This redirect appears on successfull log in:
return redirect()->intended();
So on redirect intended i get error
MethodNotAllowedHttpException. URL is correct which is defined as POST method. What am I missing here? Why does laravel redirects intended as GET method? How could I solve this problem? Thanks!
EDIT:
Route::post('/user/log-in-post', ['as' => 'user-log-in-post', 'uses' => 'UserController#postUserLogIn']);
This is my route, I hope this is one you need.
You can use a named route to solve this issue:
Lets make a named route like this:
For Get
Route::get('user/additional-fields',array(
'uses' => 'UserController#getAdditionalFields',
'as' => 'user.getAdditionalFields'
));
For post
Route::post('user/additional-fields',array(
'uses' => 'UserController#postAdditionalFields',
'as' => 'user.postAdditionalFields'
));
So we can now ensure Laravel uses the right route by doing this
return redirect()->guest(route('user.getAdditionalFields'));
Also note that its not possible to redirect a POST because Laravel expects form to be submitted. SO you can't do this:
return redirect()->guest(route('user.postAdditionalFields'));
except you use something like cURL or GuzzleHttp simulate a post request
You have to trick Laravel router by passing an "_method" the inputs.
The best way I found is by adding tricking and rewriting the Authenticate middleware
You have to rewrite the handle method to allow your redirection with your new input.
redirect()->guest('your/path')->with('_method', session('url.entended.method', 'GET'));
When you want to redirect to a route using another method than GET, simply do a Session::flash('url.entended.method', 'YOUR_METHOD').
Tell me if it do the trick
Very Simple Approach for Post method Route form Controller.
The idea behind this is, every Route always calls the Action method of a Controller. so that in that case you can directly call that method in place of Redirect action performed.
check a code sample of XYZController
$registration = Registration::find($req->regId);
$registration->update([ 'STEP_COMPLETED' => 5]); // Step 5 completed.
# Call Post Method Route
return $this->admissionFinish($req);
Note that $req should have all parameter that required in next
action Method.
change the below code in app\exceptions\handler.php
use Exception;
use Request;
use Illuminate\Auth\AuthenticationException;
use Response;
protected function unauthenticated($request,AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
//return redirect()->guest(route('login'));
return redirect()->guest('http://127.0.0.1:8000/api/signinnew'); // change this part to your login router
}
And in routes(i.e api.php):
Route::Any('signinnew', [UserLogonController::class, 'signinNew']);
This will work in laravel 8x
I know this is a routing error but I can't find any errors in my routes.
// comments
Route::get('/comments', 'CommentsController#index');
This is the controller.
/**
* Display a listing of the resource.
* GET /comments
*
* #return Response
*/
public function index()
{
return View::make('comments.create');
}
Thank you in advance. It is probably an easy 15 points to someone.
I think the problem occurs when you try to submit your form. When you use:
Route::get('/comments', 'CommentsController#index');
it's only for GET request and if you try submit your form probably you use POST method
You could add to your routes:
Route::post('/comments', 'CommentsController#index');
if you want to route to the same method in your controller or create another method and route to it.
You can also use:
Route::any('/comments', 'CommentsController#index');
if you don't care about method - all requests (including POST and GET) would be directed to the route.
Given the fact that the full routes.php file is shown, you need to add the PHP opening brackets at the top:
<?php
// comments
Route::get('/comments', 'CommentsController#index');
Omitting that will give you exactly the error you're getting.
There's two things I can think of. The first is yours route:
Route::get('/comments', 'CommentsController#index');
I think it could be either:
Route::get('comments', 'CommentsController#index'); // Note the omitted /
Route::get('comments', array('as' => 'comments', 'uses' => 'CommentsController#index');
In theory, that should fix the issue, but if not, there's one more thing I do differently when using views. You have:
return View::make('comments.create');
I use:
return View::make('comments/create');
Where the folder structure would be:
views->comments->create.blade.php
Now I have no idea if/how that would affect it, give those a try.
It looks like you have an auth filter on this route. If your AuthController is not set up, or is missing the login method, you will get a NotFoundHttpException when the auth filter in filter.php tries to redirect to your login page.