Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel始终返回带有碳的日期列_Php_Laravel - Fatal编程技术网

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();}