Laravel 提供多种方法来控制模型序列化为数组或 JSON 时日期的格式。从全局格式到特定属性的自定义,您可以确保整个应用程序中日期显示的一致性。
以下是一个在基类中设置全局日期格式的示例:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use DateTimeInterface; class BaseModel extends Model { protected function serializeDate(DateTimeInterface $date) { return $date->format('Y-m-d H:i:s'); } }
让我们来看一个在预订系统中管理不同日期格式的实际示例:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Casts\Attribute; use DateTimeInterface; class Booking extends Model { protected $casts = [ 'check_in' => 'datetime:Y-m-d', 'check_out' => 'datetime:Y-m-d', 'created_at' => 'datetime:Y-m-d H:i:s', ]; protected function serializeDate(DateTimeInterface $date) { return $date->format('Y-m-d H:i:s'); } protected function checkInFormatted(): Attribute { return Attribute::make( get: fn () => $this->check_in->format('l, F j, Y') ); } protected function duration(): Attribute { return Attribute::make( get: fn () => $this->check_in->diffInDays($this->check_out) ); } public function toArray() { return array_merge(parent::toArray(), [ 'check_in_formatted' => $this->checkInFormatted, 'duration_nights' => $this->duration, 'human_readable' => sprintf( '%s for %d nights', $this->check_in->format('M j'), $this->duration ) ]); } }
此示例展示了如何使用 $casts
属性设置特定属性的日期格式,以及如何使用 Attribute
类创建自定义访问器来生成格式化的日期和持续时间。 toArray()
方法则演示了如何将这些自定义属性添加到模型的数组表示中。
Laravel 的日期序列化功能确保了整个应用程序中日期格式的一致性,同时为特定用例提供了灵活性。
以上是定制Laravel中的型号日期格式的详细内容。更多信息请关注PHP中文网其他相关文章!