首页 > 解决方案 > Laravel 为什么我的用户模型会自动将 unix 时间戳转换为日期时间字符串

问题描述

我需要我的 api 将所有日期输出为自纪元以来的秒数,但是当我调用我的 /user 路由时,这就是我得到的:

{
"id": 1,
"name": "jk",
"email": "*****@*****",
"email_verified_at": 1619606859,
"can_add": 1,
"ip_registered": "*****",
"created_at": "2021-04-28T10:46:50.000000Z",
"updated_at": "2021-04-28T10:47:39.000000Z"
}

这是我的用户模型:

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasFactory, Notifiable, HasApiTokens;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'can_add',
        'ip_registered',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];


    protected $dateFormat = 'U';
}

如您所见,我将 dateFormat 设置为“U”。

这是我的用户表迁移:

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->unsignedInteger('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->boolean('can_add');
            $table->string('ip_registered');
            $table->unsignedInteger('created_at');
            $table->unsignedInteger('updated_at');
        });
    }

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

如您所见, created_at 和 updated_at 是整数,而不是时间戳。

最后是负责处理请求的控制器函数:

public function user(Request $request)
{
    return response()->json(User::find(Auth::id()));
}

为什么 laravel 会自动转换 updated_at 和 created_at,但不转换 email_verified_at,以及如何阻止它转换任何东西?

编辑:如果有人有同样的问题,这是我的确切解决方案:

protected function serializeDate(DateTimeInterface $date)
{
    return (int)$date->format('U');
}

标签: phpmysqllaravel

解决方案


从 Laravel 7 开始,他们已将日期序列化更改为 Carbon 的toJson方法,如升级指南中所述。要还原它,serializeDate请在模型中添加一个方法。

use DateTimeInterface;

/**
 * Prepare a date for array / JSON serialization.
 *
 * @param  \DateTimeInterface  $date
 * @return string
 */
protected function serializeDate(DateTimeInterface $date)
{
    return $date->format('Y-m-d H:i:s');
}

推荐阅读