首页 > 解决方案 > 不需要日期字段,但没有它就不会提交表单

问题描述

我正在制作一个不需要日期字段的创建帖子表单,并且我制作了一个突变器,当未在表单中输入时,使数据库中的日期为 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 不匹配”中收到验证错误。它不会提交

标签: phplaravelformsdatemutators

解决方案


您可以执行以下操作

      'published_at' => 'nullable|date_format:Y-m-d H:i:s',

在您的迁移文件中,您可以将属性设置为可为空

$table->timestamp('published_at')->nullable();

因此,如果没有值,则可以为空


推荐阅读