Form Model Binding for checkboxes

白昼怎懂夜的黑 提交于 2019-12-05 12:33:44

Works fine for me, here's a test I just did here:

Route::get('test', function() {

    $user = User::where('email','myemail@domain.com')->first();

    Form::model($user);

    $user->notify_rate = true;
    echo e(Form::checkbox('notify_rate'));

    $user->notify_rate = false;
    echo e(Form::checkbox('notify_rate'));

});

This is what I got:

<input checked="checked" name="notify_rate" type="checkbox" value="1">
<input name="notify_rate" type="checkbox" value="1">

I ended up handling this in my controller because as @Ladislav Maxa says in their comment to @Antonio Carlos Ribeiro the database never updates. This is because empty checkboxes are not submitted with the form so no 'unchecked' value is available for updating the database.

The solution I used is to check for the existence of the field in the get object. If it's there the box was checked.

$notify_rate = Input::get('notify_rate') ? 1 : 0;
$data['notify_rate'] = $notify_rate;

Another way I have done this before was to create a text input with the same name and a value of 0 before the checkbox. If the checkbox is unticked the text input value is submitted, if the checkbox is ticked it's value is used.

<input name="notify_rate" type="text" value="0">
<input name="notify_rate" type="checkbox" value="1">

That's probably not valid HTML though and I prefer dealing with this server side.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!