2015-07-02 22 views
5

Tworzę serwis internetowy w Laravel, który zwraca JSON.Laravel: Nieoczekiwane zachowanie daty w odpowiedzi JSON

Stworzyłem model Account tak:

class Account extends Eloquent { 

    // The database table used by the model. 
    // (If not defined then lowercase and plural of class name is consider as a table name) 
    protected $table = "account"; 

    // define which column can be mass assign 
    protected $fillable = array("user_id", "account_group_id", "generated_by", "image", "name", 
           "address", "zip", "area_id", "mobile", "email", "phone", "fax", 
           "website", "pan", "cst", "tin", "ecc", "iesc", "transport", 
           "other", "outstanding", "cform", "status", "mitp"); 

    // To prevent column from mass assignment. 
    protected $guarded = array('id'); 

    // Change Variable for CREATED_AT and UPDATED_AT 
    const CREATED_AT = 'itp'; 
    const UPDATED_AT = 'utp'; 
} 

ja ściągam pól z Account użyciu user_id i powrocie JSON poprzez Response::json() w moim kontrolera

$accountData = Account::select('name', 'status', 'id', 'user_id', 'utp')->where('user_id', Auth::id())->first(); 
$return = array(
       'result' => 'success', 
       'msg' => 'Login Successfully.', 
       'data' => $accountData 
       ); 
return Response::json($return); 

W tym utp zachowuje się zgodnie z oczekiwaniami i zwraca datę jako ciąg:

{ 
    "result": "success", 
    "msg": "Login Successfully.", 
    "data": { 
    "name": "Demo", 
    "status": 0, 
    "id": 143, 
    "user_id": 207, 
    "utp": "2015-07-01 18:38:01" 
    } 
} 

Jednak jeśli wezmę każdą wartość niezależnie od modelu rachunku tak:

$return = array(
    'result' => 'success', 
    'msg' => 'Login Successfully.', 
    'data' => $accountData['user_id'], 
    'account_id' => $accountData['id'], 
    'utp' => $accountData['utp'], 
    'usertype' => 'account', 
    'status' => $accountData['status'] 
); 

Wtedy to daje pewne nieoczekiwane zachowanie z utp

{ 
    "result": "success", 
    "msg": "Login Successfully.", 
    "data": 207, 
    "account_id": 143, 
    "utp": { 
    "date": "2015-07-01 18:38:01", 
    "timezone_type": 3, 
    "timezone": "Asia\\/Kolkata" 
    }, 
    "usertype": "account", 
    "status": 0 
} 

Dlaczego tak się dzieje z moim polu timestamp?

Odpowiedz

5

Ponieważ utp jest instancją Carbon\Carbon. Model::toJson (właściwie Model::toArray, ale oba są używane) obsługują zwykle i serializują datę do zwykłego formatu ISO3601-ish

Dla oczekiwanego zachowania należy sformatować instancję Carbon.

"utp" => $accountData['utp']->format("Y-m-d H:i:s"), 

Alternatywnie, rzucić go na ciąg

"utp" => (string) $accountData['utp'], 
Powiązane problemy