使用 Laravel 和 Carbon 将用户提供的 1970 年之前的日期插入到 MySql

Inserting user provided dates before 1970 to MySql using Laravel and Carbon

我正在使用以下代码:

$birthday = request('birthday_day') . "-" . request('birthday_month') . "-" . request('birthday_year');
    $birthday = Carbon::createFromFormat('d-m-Y', $birthday);
    $min_year = date('Y') - 10;

    if ($birthday->gte(Carbon::create($min_year, 1, 1))) {
        return back()->withErrors(['message' => 'You need to be at least 10 years old to sign up.'])->withInput();
    }

    $user = User::create([
        'first_name' => request('first_name'),
        'last_name' => request('last_name'),
        'email' => request('email'),
        'password' => bcrypt(request('password')),
        'birthday' => $birthday, //THE PROBLEM
        'gender' => request('gender'),
        'verified' => 0,
        'verification_code' => bcrypt(str_random(30) . request('email'))
    ]);

我在 运行 时收到以下错误消息:

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '1943-01-17 08:45:49' for column 'birthday' at row 1 (SQL: insert into `users` (`first_name`, `last_name`, `email`, `password`, `birthday`, `gender`, `verified`, `verification_code`, `updated_at`, `created_at`) values (Name, name2, example@example.com, y$qOMKZBGF4rsyEtkH2Cd5CuPDshwN7ULEKWfakrvDTrIo5KQTWTO.i, 1943-01-17 08:45:49, male, 0, y$oU88Yddwug6dgapv./REJ.NTWlCHKMXOUHVyOGd2UJXCqvHpIIW3y, 2017-03-19 08:45:49, 2017-03-19 08:45:49))

这只发生在年份小于 1970 年的日期。我读到过由于 unix 和 mysql 时间戳,这是如何发生的,但似乎无法解决这个问题。

迁移文件:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('email')->unique();
        $table->string('password');
        $table->timestamp('birthday');
        $table->string('gender');
        $table->integer('verified')->default(0);
        $table->string('verification_code')->nullable();
        $table->rememberToken();
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('users');
}
}

我认为您需要在生日栏中使用 datetime 类型:

Schema::create('users', function (Blueprint $table) {
    ...
    $table->datetime('birthday');
    ...
});

时间戳只能在 1970 年之后为正,因为它的定义