Laravel 5 表单模型绑定复选框值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38816690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5 Form Model Binding Checkbox Values
提问by Mamulasa
I am using a checkbox in a form, for some reasons I can't store the value of the checkbox status (checked or unchecked).
我在表单中使用复选框,由于某些原因,我无法存储复选框状态的值(选中或未选中)。
I am using form model binding.
我正在使用表单模型绑定。
My form is:
我的表格是:
{!! Form::model($profile, ['method' => 'PATCH', 'action' => ['ProfilesController@update', $profile->id]]) !!}
<div class="form-group">
{!! Form::label('wifi', 'Wifi') !!}
{!! Form::checkbox('wifi','yes', $profile->wifi) !!}Wifi
</div>
{!! Form::close() !!}
My Schema:
我的架构:
$table->boolean('wifi')->nullable();
But I also tried it with an integer
但我也用整数尝试过
I can't figure out what I am doing wrong
我不知道我做错了什么
回答by Zayn Ali
Your this piece of code
你的这段代码
{!! Form::checkbox('wifi','yes', $profile->wifi) !!}Wifi
is generating this
正在生成这个
<input checked="checked" name="wifi" type="checkbox" value="yes">
Which means that you are sending the value yes
to the server but your column data type is not varchar/text. You set it to boolean.
这意味着您将值发送yes
到服务器,但您的列数据类型不是 varchar/text。您将其设置为布尔值。
update your code to this because you are using form model binding
so no need to popluate it, laravel will do this for you.
将您的代码更新为此,因为您正在使用,form model binding
因此无需填充它,laravel 会为您执行此操作。
{!! Form::checkbox('wifi') !!} Wifi
Also, include your wifi
key in fillable
and casts
array. like so
另外,包括您的wifi
密钥fillable
和casts
数组。像这样
protected $fillable = [ ..., 'wifi' ];
protected $casts = [ 'wifi' => 'boolean' ];
Note:your schema code
注意:您的架构代码
$table->boolean('wifi')->nullable;
nullable
is not a property, it is a function. so update it as well
nullable
不是一个属性,它是一个函数。所以也更新它
$table->boolean('wifi')->nullable();
After that refersh your database migration
之后引用您的数据库迁移
php artisan migrate:refresh
回答by Alexey Mezenin
It depends on how are you trying to persist this data.
这取决于您如何尝试保留这些数据。
If you're using save()
method, do something like this:
如果您正在使用save()
方法,请执行以下操作:
$model->wifi = isset($request->wifi);
PS: I guess it should be ->nullable()
PS:我想应该是 ->nullable()