Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 - Multiple forms on same page?

I'm having some strange behavior with my forms in Laravel 4. I have a "settings" page with two forms, each (are supposed to) POST to a controller method, update the database and return back to the settings page. However, there seems to be an issue, either with the way my forms are working or my routes.

Here's how it is, simplified:

Settings page: (site.com/settings)

<div id="form-one" class="form-area">

{{ Form::open(array('action' => 'SettingController@editOption')) }}
   {{ Form::text('optionvalue', 'Default')) }}
   {{ Form::submit('Save Changes') }}
{{ Form::close() }}

</div>

<div id="form-two" class="form-area">

{{ Form::open(array('action' => 'SettingController@editPage')) }}
   {{ Form::text('pagevalue', 'Default')) }}
   {{ Form::submit('Save Changes') }}
{{ Form::close() }}

</div>

So basically, two seperate forms on the same page that post to two seperate methods in the same Controller - when the method is successful, it redirects them back to "settings". I won't post the methods, since tested them and they work, I believe the problem is in the routes file:

routes.php

// Checks if a session is active
Route::group(array('before' => 'require_login'), function()
{   
    Route::group(array('prefix' => 'settings'), function()
    {
        Route::get('/', 'SettingController@index');
        Route::post('/', 'SettingController@editOption');
        Route::post('/', 'SettingController@editPage');

    });
});

Now I'm pretty sure it doesn't like the two POST routes being like that, however I cannot think of another way to do it, since the forms are on the same page. I get the error:

Unknown action [SettingController@editOption].

Since the option form comes first I guess. If I take the open form blade code out (for both), it loads the page - but obviously the form doesn't do anything.

Any help would be nice! Thanks in advance.

like image 906
Alias Avatar asked Nov 02 '22 19:11

Alias


1 Answers

You can't add two same routes for different actions, because of they will be passed to first matched route and in your case to SettingController@editOption. Change your routes to :

    Route::post('/option', 'SettingController@editOption');
    Route::post('/page', 'SettingController@editPage');

Than in both actions you can redirect to '/': return Redirect::back(), and if error was occured:

if ($validation->fails())
{
    return Redirect::to('/settings')->with_errors($validation);
}
like image 64
oroshnivskyy Avatar answered Nov 07 '22 21:11

oroshnivskyy