【问题标题】:How to save a boolean value in Laravel 6?如何在 Laravel 6 中保存布尔值?
【发布时间】:2020-06-11 03:53:56
【问题描述】:

我有

迁移文件:

public function up()
{
    Schema::create('bookings', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id');
        $table->string('name');
        $table->string('phone');
        $table->boolean('wifi');
        $table->string('address');
        $table->text('desc');
        $table->timestamps();
    });
}

BookingController.phpstore方法:

public function store()
    {
        $booking = new Booking();
        $booking->user_id = 1;
        $booking->name = request('name');
        $booking->phone = request('phone');
        $booking->wifi = request('wifi');
        $booking->address = request('address');
        $booking->desc = request('desc');
        $booking->save();

        return redirect('/bookings');
    }

create.blad.phpwifi复选框的一部分:

<div class="field">
   <label for="wifi" class="label">Wi-Fi</label>
   <div class="control">
      <input type="checkbox" class="form-check" name="wifi" id="address">
   <div>
</div>

当我尝试创建记录时,出现错误:

1) 我正在尝试将值保存为 FALSE:

Illuminate\Database\QueryException SQLSTATE[23000]:完整性 违反约束:1048 列“wifi”不能为空(SQL:插入 进入bookings (user_id, name, phone, wifi, address, desc, updated_at, created_at) 值 (1, Dragon, 12341234, ?, asdfasdfasdkf hsadfasdf, asdfasdfas, 2020-02-27 07:10:55, 2020-02-27 07:10:55))

2) 当我选中 Wi-Fi 复选框时(TRUE 值)

Illuminate\Database\QueryException SQLSTATE[22007]:日期时间无效 格式:1366 不正确的整数值:列的“on” kaganat.bookings.wifi 在第 1 行(SQL:插入到 bookings (user_id, name, phone, wifi, address, desc, updated_at, created_at) 值 (1, Dragon, 12341234, on, asdfasdfasdkf hsadfasdf, asdfasdfasdfsafaa, 2020-02-27 07:17:15, 2020-02-27 07:17:15))

更新:

解决方案:

更新自

$booking->wifi = request('wifi');

$booking->wifi = request()->has('wifi');

【问题讨论】:

  • 查看文档:laravel.com/docs/6.x/requests#retrieving-input 您正在从复选框中获取名称值,而不是复选框是否被选中
  • 您能否通过展示它应该如何提交一个答案?我会尝试并接受。不幸的是,文档没有给出任何想法如何修复以及在哪里......

标签: php mysql checkbox boolean laravel-6.2


【解决方案1】:

您可以使用 has 方法检查值是否已提交,因此您可以插入 true 或 false。

您可以在文档中阅读它:https://laravel.com/docs/6.x/requests#retrieving-input

所以它必须类似于$request-&gt;has('wifi')。如果请求中存在该值,则 has 方法将返回 true。如果此值为 true,则可以将 true 分配给该字段,否则为 false。这将是我的方法。

如果需要例子,可以看这个问题Passing a boolean value from checkbox in Laravel 5.8 form

【讨论】:

  • 谢谢,我花了一些时间才弄清楚。我可以通过重构$booking-&gt;wifi = request()-&gt;has('wifi'); 来解决这个问题
猜你喜欢
  • 2017-04-25
  • 2022-08-18
  • 2015-06-04
  • 1970-01-01
  • 2011-08-01
  • 1970-01-01
  • 2020-02-19
  • 2017-08-22
  • 1970-01-01
相关资源
最近更新 更多