Jason Paddle Jason Paddle - 8 days ago 8
PHP Question

Two forms on same view in Laravel 4

I've tried number of solutions from other posts but still can't get it work.

I have two forms on the page(view)

{{ Form::open(array('action' => 'AdminController@shopMode')) }}
....// form fields

<button type="submit" class="btn btn-primary">Change</button>
{{ Form::close() }}
<hr/>
{{ Form::open(array('action' => 'AdminController@preferencesSubmit')) }}
....// second form fields

<button type="submit" class="btn btn-primary">Save Changes</button>
{{ Form::close() }}


Then in routes I have

Route::post('/admin/preferences', ['uses' => 'AdminController@preferencesSubmit', 'before' => 'csrf|admin']);
Route::post('/admin/preferences', ['uses' => 'AdminController@shopMode', 'before' => 'csrf|admin']);


When I hit submit button nothing change in database. Just page is refreshed and I got success message from FIRST form even if I submit second one.

Is it because url's in routes are same for both posts?

Update: First form input field:

<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" <?php if ($settings['preferences_shop_mode'] == 0){ ?> checked="checked" value="1"<?php }else{ ?> value="0" <?php } ?>>


Here I check if preference is =0 to set value to 1 otherwise value = 0. In source I see that value is
=1
which is correct because in database I have
0


<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked="checked" value="1">


This is the controller

public function shopMode() {

$preferences = Preferences::where('preferences_id', 1)->first();
if (!$preferences) {
App::abort(404);
}

Input::merge(array_map('trim', Input::all()));

$preferences->preferences_shop_mode = Input::get('onoffswitch');
$preferences->save();
return Redirect::to('/admin/preferences')->with('message', 'Shop mode changed successfully.');
}


Any idea why isn't updated in database?

Answer

Routes are read in cascade. Since both routes have the same path, the first takes priority (an entry was found, so no further route lookup is needed).

You should split them with just different paths, for example:

Route::post('/admin/preferences/general', ['uses' => 'AdminController@preferencesSubmit', 'before' => 'csrf|admin']);
Route::post('/admin/preferences/shop', ['uses' => 'AdminController@shopMode', 'before' => 'csrf|admin']);