Laravel Collective HTML checkboxes form value 'on' instead of '1' is causing issues while add|update a DB element

2.8k views Asked by At

I am using Laravel Collective HTML and I am creating a form as follow:

{!! Form::model($band, ['method' => 'PATCH','route' => ['bands.update', $band->id]]) !!}
<div class="row">
    <div class="col-xs-4 col-sm-4 col-md-4">
        ...
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Still active?:</strong>
                {!! Form::checkbox('still_active', null, array('class' => 'form-control')) !!}
            </div>
        </div>
        ...
    </div>
</div>
{!! Form::close() !!}

It works fine, meaning if the value of still_active coming from DB is 1 the checkbox is shown checked or unchecked if value is 0. If I check and option and try to save the element I got the following error:

QueryException in Connection.php line 770:
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'on' for column 'still_active' at row 1 (SQL: update `bands` set `start_date` = 2016-12-26, `still_active` = on, `updated_at` = 2016-12-26 22:58:19 where `id` = 47)

I have check the form data sent to the server and I can see still_active set to on instead of 1:

_method:PATCH
_token:PtVu9DCMcV0EXlJRAKxMOOkobNWL2O2bbKhNWRtV
name:Nayeli Hoppe
start_date:2016-12-26
website:https://bogisich.com/accusamus-sequi-aspernatur-et.html
still_active:on

This is the method processing the data on the Controller:

public function update(Request $request, $id)
{
    $this->validate($request, [
        'name'       => 'required',
        'start_date' => 'required',
        'website'    => 'required',
    ]);

    Band::find($id)->update($request->all());

    return redirect()->route('bands.index')
        ->with('success', 'Band updated successfully');
}

How I can avoid this? Do I need to transform the data on the controller before save it?

1

There are 1 answers

0
CUGreen On BEST ANSWER

try {!! Form::checkbox('still_active', 1, null, array('class' => 'form-control')) !!}

Here is some reference.