0
votes

I'm trying to build a page with two forms, both are set method="post", as well as a submit <button> for each form. The submit action of first form is handled by FirstController, and the second one is handled by SecondController. In the route file web.php, I need to declare two route functions for each submit button, and I want to keep the same url, but there is no way the button will know which post it should call. I saw some solutions about creating jobs to handle each button, but anyway can I tell Laravel which post route to call?

The skeleton is like this:

web.php

Route::post('/', 'FirstController@store');

Route::post('/', 'SecondController@sendEmail');

FirstController.php

class FirstController extends Controller
{
    public function store()
    {
        /*
            create a new entry to the data base
        */
    }
}

SecondController.php

class SecondController extends Controller
{
    public function sendEmail()
    {
        Mail::to('recipient@abc.com')->send(new SampleMail());
    }
}
2
"I want to keep the same url" Why? Process the POST, then redirect back to / when you're done.ceejayoz
@ceejayoz Hi. The reason is that the whole page has two buttons, the first one is to create new entry to database, and the second is to confirm the entry created and send an email. Neither of this should redirect the user to a new page.keanehui
A POST is always going to "redirect the user to a new page" (even if it's the same URL) unless you do some AJAX, at which point the URL doesn't matter anyways. Your two forms can POST to different URLs; those URLs can both redirect back to /.ceejayoz

2 Answers

3
votes

you can't use the same URL with the same method such as POST, GET whatever. What you can do is just pass some parameters to identify whether it for sending mail or store data. But you have to it in the same controller and the same function. I do not recommend you to do that because it violates the single responsibility principle in SOLID. Just Write two routes with different URL and do that. If essential to maintain the same URL, you can do it with GET and POST method.

-1
votes

I'm not sure why one of your controllers can't handle both of those functions, but if you really want to seperate those steps and not redirect the user, you should use ajax on at least the first step.