Laravel 请求中不需要的参数不能为空

Laravel unrequired parameter in request can not be null

你好,我的问题是,当我 post 数据从表单到我的控制器时,它会弹出一个错误,说我的列不能为空。

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'date' cannot be null (SQL: insert into `tasks` (`body`, `importance`, `date`, `updated_at`, `created_at`) values (qqqqqq, i_u, , 2018-01-25 22:29:16, 2018-01-25 22:29:16))

看来这一栏必须填写,但我希望它是可选的。 我试图将其设置为 null 作为默认值,但它没有用。 事实上,当列被填满时,一切正常。 问题是我希望可选地填充此输入。

这是源码请大家帮忙。(我猜都是关于日期的)

我的表格

 <form class="form-inline" method="post" action="/planer/public/">
            {{ csrf_field() }}

            {{--Describtion of a taks--}}
            <div class="form-group mb-2">

            {{--Importance--}}
            <div class="form-group  mx-sm-3 mb-2">
                <select class="form-control" name="importance">
                    <option value="i_u">Ważne pilne</option>
                    <option value="i_nu">Ważne mniej pilne</option>
                    <option value="ni_u">Mniej ważne pilne</option>
                    <option value="ni_nu">Mniej ważne mniej pilne</option>



                </select>
            </div>

            {{--Date--}}
            <div class="form-group mb-2"> <!-- Date input -->
                <input class="form-control" id="date" name="date" placeholder="Day/Month/Hour" type="text" value=""/>
            </div>

        <button type="submit" class="btn btn-primary mb-2">Dodaj</button>

        </form>

来自 web.php

的路线
Route::get('/','TasksController@index');

路线::post('/','TasksController@store');

路线::删除('/{任务}','TasksController@destroy');

我的table

public function up()
{
    Schema::create('tasks', function (Blueprint $table) {
        $table->increments('id');
        $table->string('body');
        $table->string('importance');
        $table->string('date');
        $table->timestamps();
    });
}

还有我的控制器

 public function store(){
    $this->validate(request(),[
        'body'=>'required',
        'importance'=>'required'
    ]);

    Task::create([
        'body'=>request('body'),
        'importance'=>request('importance'),
        'date'=>request('date')
    ]);
    return redirect('/');
}

如果您希望某个列在插入时是可选的,则必须在迁移中将其标记为 nullable

public function up()
{
    Schema::create('tasks', function (Blueprint $table) {
        $table->increments('id');
        $table->string('body');
        $table->string('importance');
        $table->string('date')->nullable();
        $table->timestamps();
    });
}

相关文档在此处:https://laravel.com/docs/5.5/migrations#column-modifiers

您可以修改已在迁移中使用 changes() 方法创建的列,例如:

  1. php artisan make:migration set_date_nullable --table=tasks

  2. 编写迁移:

    Schema::table('tasks', function (Blueprint $table) {
        $table->string('date')->nullable()->change();
    });
    
  3. 运行 php artisan migrate

相关文档在此处:https://laravel.com/docs/5.5/migrations#modifying-columns

P.s:检查 date 列类型,而不是 string.