在 Laravel 8 请求 class 中处理布尔值的最佳方式/最佳实践是什么?

What's the best way / best practice to handle boolean in a Laravel 8 Request class?

我有一些定义特定布尔值的标准单复选框,即 is_active

 <label class="form-check-label text-google">
   <input type="checkbox" name="is_active" id="is_active" value="1" class="form-check-input"
      @if (old('is_active') == '1' || (empty(old()) && $doctor->is_active == 1)) checked @endif>
      {{ __('Doctor activated') }}
      <i class="input-helper"></i>
 </label>

将请求发送到我的控制器时,该请求通过自定义请求 class 运行,我目前在其中执行以下操作。主要是更新方法很重要,所以取消选中的复选框将在数据库中更新。

  /**
  * Get the validation rules that apply to the request.
  *
  * @return array
  */
  public function rules()
 {
   $this->request->set("is_active", $this->request->has("is_active"));

   return [ ...

我还将模型中的 is_active 属性 转换为布尔值。 这里的最佳做法是什么?我找不到任何可以引导我走向正确方向的东西...

提前致谢。

既然你想在验证之前触摸请求,你可以使用这个方法:prepareForValidation():

Prepare Input For Validation

If you need to prepare or sanitize any data from the request before you apply your validation rules, you may use the prepareForValidation method:

use Illuminate\Support\Str;

/**
 * Prepare the data for validation.
 *
 * @return void
 */
protected function prepareForValidation()
{
    $this->merge([
        'slug' => Str::slug($this->slug),
    ]);
}

所以在你的情况下你可以这样做:

public function prepareForValidation()
{
    $this->merge([
        'is_active' => $this->request->has('is_active')),
    ]);
}

正如我所读,您想知道是否有值,事实上我认为您可以使用 class 请求 filled 函数。