gpt4 book ai didi

php - 在用户的时区(Laravel)中显示模型上的所有日期

转载 作者:行者123 更新时间:2023-12-02 01:00:38 24 4
gpt4 key购买 nike

我有用户 timezone存储(在 timezone DB 表中有 users 列),我想显示 全部 $dates 上的属性所有型号 在用户的时区中,如果 已认证 .

我试图找到一种优雅的方式来做到这一点......理想情况下,当 Blade View 中有这样的东西时:

{{ $post->created_at }}

OR

{{ $post->created_at->format('h:i:s A') }}

...对于经过身份验证的用户,它将自动在他们的时区中。

你会如何处理这件事?

我正在考虑创建一个特征(例如, app/Traits/UserTimezoneAware.php )并将其放置在那里 accessors这将简单地返回 Carbon::createFromFormat('Y-m-d H:i:s', $value)->timezone(auth()->user()->timezone)如果当前用户已通过身份验证。例如:
<?php

namespace App\Traits;

use Carbon\Carbon;

trait UserTimezoneAware
{
/**
* Get the created_at in the user's timezone.
*
* @param $value
* @return mixed
*/
public function getCreatedAtAttribute($value)
{
if (auth()->check()) {
return Carbon::createFromFormat('Y-m-d H:i:s', $value)->timezone(auth()->user()->timezone);
}

return Carbon::createFromFormat('Y-m-d H:i:s', $value);
}

/**
* Get the updated_at in the user's timezone.
*
* @param $value
* @return mixed
*/
public function getUpdatedAtAttribute($value) { ... }
}

但我不确定这样做是好是坏(为 Laravel 的 $dates 属性创建这些访问器)?

此外,模型将具有 不同 $dates 中指定的属性数组:例如, User模型可以有:
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [
'created_at',
'updated_at',
'last_login_at'
];

Post模型可以有:
protected $dates = [
'created_at',
'updated_at',
'approved_at',
'deleted_at'
];

是否可以动态根据 $dates 中指定的属性,在 trait 中创建访问器使用该特征的模型数组?

或者也许有更好的方法来处理这个问题,而无需访问器?

最佳答案

一种方法(没有访问器)是使用这个特性:

<?php

namespace App\Traits;

use DateTimeInterface;
use Illuminate\Support\Carbon;

trait UserTimezoneAware
{
/**
* Return a timestamp as DateTime object.
*
* @param mixed $value
* @return \Illuminate\Support\Carbon
*/
protected function asDateTime($value)
{
$timezone = auth()->check() ? auth()->user()->timezone : config('app.timezone');

if ($value instanceof Carbon) {
return $value->timezone($timezone);
}

if ($value instanceof DateTimeInterface) {
return new Carbon(
$value->format('Y-m-d H:i:s.u'), $timezone
);
}

if (is_numeric($value)) {
return Carbon::createFromTimestamp($value)->timezone($timezone);
}

if ($this->isStandardDateFormat($value)) {
return Carbon::createFromFormat('Y-m-d', $value)->startOfDay()->timezone($timezone);
}

return Carbon::createFromFormat(
str_replace('.v', '.u', $this->getDateFormat()), $value
)->timezone($timezone);
}
}

使用此特征时,我们将覆盖 asDateTime($value)定义于 Concerns\HasAttributes trait(在 Illuminate\Database\Eloquent\Model 中使用)。

这似乎工作正常,我还没有遇到任何问题。

但我不确定这样做时是否有任何风险或潜在问题(当使用覆盖 asDateTime 方法的这个特征时)。

关于php - 在用户的时区(Laravel)中显示模型上的所有日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50768490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com