2017-06-15 60 views
2

有沒有一種方法可以始終使用碳排序列返回日期?Laravel總是使用碳返回日期列

假設我有一個Challenges模型/表與date_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獲取日期但有一個更清潔的方式?

+0

https://laravel.com/docs/5.4/eloquent-mutators#date-mutators – castis

回答

5

正如@Castis指出的那樣,您可以使用屬性mutators和訪問器來修改數據,並將其發送到模型以及來自模型。例如,在你的情況下定義getCreatedAtAttribute方法,並從中返回Carbon和created_at字段解析成它。

+0

我剛剛使用'公共函數getDateEndAttribute($值){ $結束=新碳($值); return $ end-> diffForHumans(); }' – Packy

2

在你的模型,你可以將它們添加到protected $dates陣列宣佈哪些列應該被轉換爲Carbon實例:

protected $dates = ['created_at', 'updated_at', 'date_end']; 

當然,如果你使用的->timestamps()方法前兩個是隻需要你的遷移。

+0

我現在有''保護$日期= ['date_start','date_end',];'在我的'challenge.php '模型和它返回相同的日期,而不是碳 – Packy