【问题标题】:How do I format the date before updating in Laravel, using vuejs-datepicker如何使用 vuejs-datepicker 在 Laravel 中更新之前格式化日期
【发布时间】:2021-09-23 11:12:49
【问题描述】:

我正在使用 vuejs-datepicker 和惯性js,但是当我尝试更新数据库时出现错误: 日期时间格式无效:1292 日期值不正确:“date_of_birth”列的“2021-07-09T12:54:00.000Z”

我尝试在控制器中格式化日期,但这并没有保存任何内容。我在这里错过了什么?

eidt.vue:

<datepicker v-model="form.date_of_birth" name="Date of birth" />

data() {
      return {
        form: this.$inertia.form({
          _method: 'put',
          date_of_birth: this.application.date_of_birth,
        }),
      }
},

methods: {
      update() {
          this.form.put(this.route('applications.update', this.application.id))
      },
},

控制器/应用程序.更新:

User::find($application->user_id)->update(Request::only(
     ['date_of_birth' => date('Y-m-d H:i:s', $application->user->date_of_birth)],
));

【问题讨论】:

    标签: laravel vue.js inertiajs


    【解决方案1】:

    尝试使用以下方法:

    User::find($application->user_id)
        ->update([
            'date_of_birth' => Carbon::parse(request()->date_of_birth)->toDateTimeString()
        ]);
    

    根据来自前端的日期,您需要将date_of_birth 解析为数据库将接受的日期时间字符串。

    这可以通过使用上面的Carbon::parse($value)-&gt;toDateTimeString() 方法来完成。

    确保将Carbon 导入控制器:

    use Carbon\Carbon

    【讨论】:

      【解决方案2】:

      这就是我们的做法,对于表单中的每个日期选择器日期,我们都会在模型上设置一个设置器,例如

      public function setDateOfBirthAttribute($value): void
      {
          $this->attributes['date_of_birth'] = $value ? Carbon::parse($value) : null;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-02
        相关资源
        最近更新 更多