Php Laravel始终返回带有碳的日期列
是否有一种方法可以始终使用碳元素返回列中的日期 假设我有一个Php Laravel始终返回带有碳的日期列,php,laravel,Php,Laravel,是否有一种方法可以始终使用碳元素返回列中的日期 假设我有一个Challenges模型/表,其中包含date\u end列 当我在我的ChallengesController中执行此调用时,它将以json格式为我的应用程序返回所有challenges: public function index() { return response()->json([ 'status'=>'success', 'challenges' =>
Challenges
模型/表,其中包含date\u end
列
当我在我的ChallengesController
中执行此调用时,它将以json格式为我的应用程序返回所有challenges
:
public function index()
{
return response()->json([
'status'=>'success',
'challenges' => Auth::user()->challenges,
]);
}
但日期仍然是MySQL格式。我知道我能做到:
public function index()
{
$challenges = Auth::user()->challenges;
foreach ( $challenges as $challenge){
$challenge['humandate'] = $challenge->date_end->diffForHumans();
}
return response()->json([
'status'=>'success',
'challenges' => $challenges,
]);
}
然后通过
challenge.humandate
获取日期,但是有更干净的方法吗?在您的模型中,您可以通过将哪些列添加到受保护的$dates
数组中来声明哪些列应转换为Carbon
实例:
protected $dates = ['created_at', 'updated_at', 'date_end'];
当然,只有在迁移中使用
->timestamps()
方法时,才需要前两种方法。正如@Castis所指出的,当数据进入模型和来自模型时,可以使用属性变异器和访问器来修改数据。例如,在您的例子中,定义GetCreateDataAttribute方法,并从中返回Carbon和解析到其中的created_at字段。我目前有:protected$dates=['date_start','date_end',]在我的challenge.php
模型中,它返回相同的日期,而不是刚刚使用的carbonI公共函数getDateEndAttribute($value){$end=new Carbon($value);return$end->diffForHumans();}