2017-02-03 101 views
1

目前,當我轉換一個模型爲JSON,所有的碳日期字段鑄像這樣:Laravel:在模型碳日期更改格式時轉換成JSON

"end_time": { 
    "date": "2017-02-03 23:59:00.000000", 
    "timezone_type": 3, 
    "timezone": "Europe/London" 
} 

我希望它使用Atom符號鑄造。 這可以在碳做到像這樣:

$order->end_time->toAtomString() 

其中$dateCarbon日期。

如何在將模型轉換爲JSON時將模型轉換爲原子格式的日期?

我知道,這是可以附加數據,像這樣:https://laravel.com/docs/5.3/eloquent-serialization#appending-values-to-json

但這並不改變現有值的格式?

回答

1

只要您願意使用與「end_time」不同的名稱,您提供的鏈接應該是您的解決方案。你可以附加「end_time_formatted」,或類似的東西。

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Event extends Model 
{ 

    protected $appends = ['end_time_formatted']; 

    public function getEndTimeFormattedAttribute() 
    { 
     return $this->end_time->toAtomString(); 
    } 
} 

然後,無論何時您將模型轉換爲json,它都會包含「end_time_formatted」。

另一種選擇(如果您需要保留相同的名稱)將通過將toJson方法複製到模型中來覆蓋toJson方法。我可能會建議不要這樣做,但是它會阻止在將它投射到JSON之前每次都要說$this->created_at = $this->created_at->toAtomString()

/** 
    * Convert the model instance to JSON. 
    * 
    * @param int $options 
    * @return string 
    * 
    * @throws \Illuminate\Database\Eloquent\JsonEncodingException 
    */ 
    public function toJson($options = 0) 
    { 
     $atom = $this->created_at->toAtomString(); 
     $json = json_encode($this->jsonSerialize(), $options); 

     if (JSON_ERROR_NONE !== json_last_error()) { 
      throw JsonEncodingException::forModel($this, json_last_error_msg()); 
     } 
     $json = json_decode($json); 
     $json->created_at = $atom; 
     $json = json_encode($json); 

     return $json; 
    } 

我是不是能夠得到這個通過在方法的頂部將值更改爲工作,所以我被迫json_decode,然後重新編碼,它不給我感覺好極了。如果你確實使用這條路線,我會建議深入挖掘一下,試着讓它工作而不需要解碼。

0

另一種使用是格式化你從模型

收到你可以使用它你的約會對象轉換到想要使用碳格式的輔助方法,你的約會。

碳利於格式的能力,我覺得這是你在找什麼:

your_function_name($created_at_date, $format = "jS M Y") 
{ 
    $carbon = new \Carbon\Carbon($created_at_date); 
    $formatted_date = $carbon->format($format); 

    return $formatted_date; 
    } 

希望這有助於。

2

隨着恢復殭屍的風險,我將呈現一個替代的解決這個問題:

覆蓋由性狀HasAttributes定義的serializeDate方法:

/** 
* Prepare a date for array/JSON serialization. 
* 
* @param \DateTimeInterface $date 
* @return string 
*/ 
protected function serializeDate(DateTimeInterface $date) 
{ 
    return $date->toAtomString(); 
}