php - 不需要日期字段,但没有它就不会提交表单
问题描述
我正在制作一个不需要日期字段的创建帖子表单,并且我制作了一个突变器,当未在表单中输入时,使数据库中的日期为 NULL。
create.blade.php 中的表单
<div class="form-group {{ $errors->has('published_at') ? 'has-error' : '' }}">
{!! Form::label('published_at', 'Publish date') !!}
{!! Form::text('published_at', null, ['class' => 'form-control', 'placeholder' => 'Y-m-d H:i:s']) !!}
@if($errors->has('published_at'))
<span class="help-block">{{ $errors->first('published_at') }}</span>
@endif
</div>
Post.php 中的突变体:
public function setPublishedAtAttribute($value)
{
$this->attributes['published_at'] = $value ?: NULL;
}
控制器中的存储功能:
$this->validate($request, [
'title' => 'required',
'slug' => 'required|unique:posts',
'body' => 'required',
'published_at' => 'date_format:Y-m-d H:i:s',
'category_id' => 'required'
]);
当未在表单中输入时,我希望数据库中的日期为 NULL,但我在“发布的日期与格式 Ymd H:i:s 不匹配”中收到验证错误。它不会提交
解决方案
您可以执行以下操作
'published_at' => 'nullable|date_format:Y-m-d H:i:s',
在您的迁移文件中,您可以将属性设置为可为空
$table->timestamp('published_at')->nullable();
因此,如果没有值,则可以为空
推荐阅读
- google-sheets - Way to overwrite specific column data based on new form response?
- javascript - 在反应中调用儿童中的函数?
- sql - Convert string in HH:MM:SS format to seconds in Google BigQuery (Standard SQL)
- python - Cannot get groupby records based on their minimum value using pandas in python
- javascript - 让工具提示在一段时间后消失
- haskell - 导管:怎么样?具有背压的多个生产者到一个消费者
- unity3d - 如何要求公共变量(预制件)在 UNITY 中具有某个组件(刚体)?
- numpy-slicing - 切片一个 Numpy 数组给出错误的结果
- sql - 根据特定条件拆分 SQL 列
- java - Java 三元运算符错误地评估 null