日期和时间戳格式以及唯一规则

时间:2019-05-25 17:19:39

标签: laravel laravel-5

我有这次迁移:

   Schema::create('atp_players', function (Blueprint $table) {
        $table->bigIncrements('id');

        $table->string('first_name');
        $table->string('last_name');
        $table->date('birthdate');
        $table->bigInteger('geo_country_id')->unsigned();
        $table->boolean('retired')->default(0);

        $table->softDeletes();
        $table->timestamps();

        $table->foreign('geo_country_id')->references('id')->on('geo_countries')->onDelete('cascade')->onUpdate('cascade');
    });

我的第一个问题是,当我收到o存储一个实例时,我将所有字段作为字符串接收。

邮递员的结果:

  {
    "first_name": "Tomas",
    "last_name": "berdych",
    "birthdate": "1988-08-10",
    "geo_country_id": "1",
    "updated_at": "2019-05-25 14:13:41",
    "created_at": "2019-05-25 14:13:41",
    "id": 12
  }

控制器:

 public function store(ATPPlayerRequest $request)
  {
    return ATPPlayer::create($request->all());
  }

第二个问题是唯一规则不适用于d-m-Y格式。

 return [
        'first_name' => ['required'],
        'last_name' => ['required'],
        'birthdate' => ['required', 'date','date_format:d-m-Y', 'unique:atp_players,birthdate'],
        'geo_country_id' => ['required','exists:geo_countries,id']
    ];

在模型中,我使用了accesor:

   public function setBirthdateAttribute($value)
   {
    $this->attributes['birthdate'] = date('Y-m-d', strtotime($value));
   }

如果我使用转换器来格式化created_at或Deleted_at

$ value-> format(..)->这不起作用,因为我收到的是字符串而不是时间戳!

1 个答案:

答案 0 :(得分:2)

尝试通过casting on model强制输入类型。喜欢:

    protected $casts = [
        'geo_country_id' => 'integer',
        'birthdate' => 'date',
        ...
    ];