I have two forms on a page both submits the data via POST method
. I want to handle both requests on the same url i.e /home and use different controllers and methods for both forms. Below are the two routes.
Route::post('home' ,'FacebookControllers\PostsController@save');
Route::post('home' , 'FacebookControllers\MessageController@storeMessage');
In PostsController@save
I am checking
if(isset($_POST['submitPost']) && $_SERVER['REQUEST_METHOD']=='POST'){
//do something
}
and in MessageController@storeMessage
I am doing the same for other form
if(isset($_POST['sendMessage']) && $_SERVER['REQUEST_METHOD']=='POST'){
return "got it";
}
The problem is that only second route works. I don't if I am doing right or wrong. Please lead me to the right direction.
If the purpose is only to maintain the URL that appears in the browser, you may apply a trick in which you submit your post request to different ROUTES that are specifically exist for processing purpose and then redirect back to the same URL.
For example:
Then in your view , you maybe have two diffrent forms in the same view:
Now in your controller, in the both actions do something like :
By doing so, the URL will remain same for the user, after the process is done the user will be redirected back to the same URL with the status.
May be this is not a good coding practice, but it solve the problem by maintaining the same URL while having multiple posts to the same controller in the same view.
The most important point here is that you have to strictly prevent an error during the process by using conditions and redirect to the same URL in case of any problem, otherwise the action will try to show the user the tricky ROUTE (yoursite.com/message) for any error.
won't work - how should laravel determine where to post to? The way I would go is to create two jobs and one route, then check for the value in
Request
and dispatch the correct job.First, create two job classes with
The generated file will look much like this:
In the job's
handle()
method you can do what you wanted to do in your Controller.Now the route, let's do
and according to this in your PostsController, add a method (I called it findAction) like this:
This way the correct action will be performed depending on the submitted value.
Change the job's constructor to something like:
And you can access the submitted values from the forms you have submitted inside the job's
handle()
method with$this->data