【问题标题】:What's the best way / best practice to handle boolean in a Laravel 8 Request class?在 Laravel 8 Request 类中处理布尔值的最佳方式/最佳实践是什么?
【发布时间】:2021-11-25 22:36:07
【问题描述】:

我有一些标准的单个复选框,它们定义了一个特定的布尔值,即 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>

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

  /**
  * 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 属性转换为布尔值。 这里的最佳做法是什么?我找不到任何能引导我走向正确方向的东西...

提前致谢。

【问题讨论】:

  • 你的问题不是很清楚。就我所见,您将表单的is_active 属性设置为1,然后您想在验证之前在Request 对象中覆盖此值,这是您正在尝试的吗?
  • 是的,这就是我想要实现的目标

标签: laravel eloquent request laravel-8


【解决方案1】:

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

为验证准备输入

如果您需要在之前准备或清理请求中的任何数据 你应用你的验证规则,你可以使用 prepareForValidation 方法:

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')),
    ]);
}

【讨论】:

  • 太好了,prepareForValidation 是我一直在寻找的方法......但是,您的旁注并不能解决问题,因为复选框在取消选中时不会发送任何值,我需要 false取消选中的复选框
【解决方案2】:

当我读到你想知道是否有值时,事实上我认为你可以使用类 Request filled 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    • 2013-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多