【问题标题】:Laravel 5 Form Model Binding Checkbox ValuesLaravel 5 表单模型绑定复选框值
【发布时间】:2023-04-03 22:07:01
【问题描述】:

我在表单中使用复选框,由于某些原因,我无法存储复选框状态(选中或未选中)的值。

我正在使用表单模型绑定。

我的表格是:

{!! 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() !!}

我的架构:

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

但我也用整数尝试过

我不知道我做错了什么

【问题讨论】:

    标签: php forms laravel checkbox


    【解决方案1】:

    这取决于您如何尝试持久化这些数据。

    如果您使用save() 方法,请执行以下操作:

    $model->wifi = isset($request->wifi);
    

    PS:我猜应该是-&gt;nullable()

    【讨论】:

    • 嗨,Alexey,我正在使用: public function update(ProfileRequest $request, $id) { $profile = Profile::findOrFail($id); $profile->update($request->all());返回重定向('后端/配置文件'); }
    • 然后尝试在$profile-&gt;update($request-&gt;all()); 之前执行此操作$request-&gt;wifi = isset($request-&gt;wifi);。而且,在您的情况下,您应该在 $fillable 模型的 Profile 数组中包含 wifi
    • 好的,wifi 在可填充数组中,我将控制器更新为: public function update(ProfileRequest $request, $id) { $profile = Profile::findOrFail($id); $request->wifi = isset($request->wifi); $profile->update($request->all());返回重定向('后端/配置文件'); } 但还是一样 :(
    • 究竟是什么不起作用?你有什么错误吗?如果没有,'dd(iseet($request->wifi))` 在复选框被选中和不被选中时会说什么?
    【解决方案2】:

    你的这段代码

    {!! Form::checkbox('wifi','yes', $profile->wifi) !!}Wifi
    

    正在生成这个

    <input checked="checked" name="wifi" type="checkbox" value="yes">
    

    这意味着您将值 yes 发送到服务器,但您的列数据类型不是 varchar/text。您将其设置为布尔值。

    将您的代码更新为此,因为您使用的是form model binding,因此无需填充它,laravel 会为您完成。

    {!! Form::checkbox('wifi') !!} Wifi
    

    另外,将您的wifi 密钥包含在fillablecasts 数组中。像这样

    protected $fillable = [ ..., 'wifi' ];
    
    protected $casts = [ 'wifi' => 'boolean' ];
    

    注意:您的架构代码

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

    nullable 不是属性,而是函数。所以也更新一下

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

    然后引用您的数据库迁移

    php artisan migrate:refresh
    

    【讨论】:

    • 嗨 Zayn,谢谢。我使用了您的示例,并更新为 nullable()。还是一样,状态没有保存到DB中
    • 是的,我已经刷新了我的迁移
    • 好的,在您的模型中,您是否将 wifi 放入您的可填充对象和 casts 数组中?像这样protected $casts = [ 'wifi' =&gt; 'boolean' ];
    • 扎恩,太棒了!!!!太感谢了。我从来没有听说过属性铸造。成功了
    • 太棒了!我很高兴它有帮助:)
    猜你喜欢
    • 2018-06-21
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 2013-11-02
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多