简体   繁体   English

Laravel 5表单模型绑定复选框值

[英]Laravel 5 Form Model Binding Checkbox Values

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 我无法弄清楚我做错了什么

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. 这意味着您将值yes发送到服务器,但您的列数据类型不是varchar / text。 You set it to boolean. 您将其设置为布尔值。

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. 此外 ,将您的wifi密钥包含在fillablecasts数组中。 like so 像这样

protected $fillable = [ ..., 'wifi' ];

protected $casts = [ 'wifi' => 'boolean' ];

Note: your schema code 注意:您的架构代码

$table->boolean('wifi')->nullable;

nullable is not a property, it is a function. nullable不是属性,它是一个函数。 so update it as well 所以也要更新它

$table->boolean('wifi')->nullable();

After that refersh your database migration 在那之后引用您的数据库迁移

php artisan migrate:refresh

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM