在 Laravel 5 中将复选框添加到数据库

Add Checkbox to database in Laravel 5

我在 html 和数据库方面不是 100% 出色,但我已经达到了。我所做的工作有效,但在我编辑具有复选框的页面时无效。

在我的数据库迁移中:

$table->string('check_this')->nullable();

观看次数:

<div class="checkbox">
    @if ($job->check_this == 'selected')
         <label><input type="checkbox" name="check_this" value="selected" checked>Yes.</label>
    @else
         <label><input type="checkbox" name="check_this" value="selected">Yes.</label>
   @endif
</div>

选中复选框后,它会写入数据库,因此我的 if 语句将无法正常工作。有没有一种方法可以在未选中的情况下从数据库中删除该值?

也许我的做法是错误的,因为迁移中的复选框格式正确。

您的迁移应如下所示: $table->boolean('check_this');

和视图部分: @if ($job->check_this)

请参阅:http://laravel.com/docs/master/schema#adding-columns,了解 Laravel 中 'columns' 的所有播出信息类型。

复选框如果没有选中则不会发送任何内容,因此数据库不会更新,除非您签入控制器并且如果 "check_this" 未在您的请求中设置,请在数据库中将其设置为 0。

$obj = Obj::find($id); //get your object from database 
$input = Request::all(); //or $request->all() if you use requests
if(!isset($input['check_this'])){
 $input['check_this'] = 0; //or whatever you want
}
$obj->fill($input);
$obj->save();

注意: 您可以简化视图

<div class="checkbox">
     <label><input type="checkbox" name="check_this" value="selected" @if ($job->check_this == 'selected') checked @endif>Yes.</label>
</div>

当然,如果您不需要这个特定的字符串,那么关于在该字段中使用布尔值的答案将优化您的数据库。