php - 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');
}
解决方案
从 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');
}
推荐阅读
- react-native-android - react-native android构建缓慢
- java - 为什么我无法在 MacOS 上加载我的 pkcs11 库来调试 java 进程?
- sql - 将单元格中的字符拆分为单独的列
- c# - 包含重复的 BondCodegen 项目
- javascript - 如何在Vuejs中鼠标悬停时隐藏div元素?
- javascript - 是的,如果值输入以 0 开头,则不会触发错误
- docker - Netty 套接字通道可以序列化吗?
- java - 是否可以在 Wildfly/JBoss 上使用 javaagent 部署和运行战争应用程序?
- java - 如何使用新文本使单个 TextView 淡入淡出
- python - 如何使用 pandas 数据框跟踪数据错误?