Jeff P. Jeff P. - 1 year ago 87
PHP Question

Laravel 4 PHP: Editing a form with 'unchecked' checkboxes produces an 'undefined index' error

I have an edit form containing several checkboxes. When I try to update the form with any of the checkboxes left 'unchecked', I get an "undefined index" error for that particular checkbox. When I initially store new data, 'unchecked' checkboxes are stored just fine. It's only an issue if I try to edit data and leave checkboxes 'unchecked'.

I've tried using the '{{Form::hidden(fieldname, 0) }}' method but it hasn't been working for me.


{{ Form::model($album, array('method' => 'PUT', 'route' => array('edit_album2', $album->album_id))) }}

<div class ="form-group">

{{ Form::checkbox('album_application_kitchen', 'Kitchen') }}
{{ Form::label('album_application_kitchen', 'Kitchen') }}
{{ Form::checkbox('album_application_bathroom', 'Bathroom') }}
{{ Form::label('album_application_bathroom', 'Bathroom') }}<br />


{{ Form::close() }}


public function update($id) {

$input = \Input::all();

$validation = new Validators\Album($input);

if ($validation->passes())
$album = Album::find($id);
$album->album_application_kitchen = $input['album_application_kitchen'];
$album->album_application_bathroom = $input['album_application_bathroom'];

return \Redirect::route('', array('id' => $id));
/* Code for when validation fails */

Is there a special trick to solve this problem or am I just not using the {{Form::hidden()}} structure properly?

Answer Source

In your controller, when you assign Input::all() to $input, no element gets added to the $input array for unchecked checkboxes, because they don't exist in the Input::all() array (unchecked checkboxes don't get passed in POST.) When updating, use Input::get() instead, which will return null if there is no value for an input, as is the case with any unchecked checkboxes:

$album->album_application_kitchen = Input::get('album_application_kitchen');  
$album->album_application_bathroom = Input::get('album_application_bathroom');

Besides, $input = Input::all() is redundant anyway, since Input::all() is already an array. Just pass Input::all() to your validator.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download