Laravel "Unexpected data found" error when trying to change format of Carbon created_at date

chipit24 picture chipit24 · Aug 10, 2014 · Viewed 53.6k times · Source

When I try to modify the format of the default created_at field of my Resource model, I get the following error:

{  
   "error":{  
      "type":"InvalidArgumentException",
      "message":"Unexpected data found.
                 Unexpected data found.
                 The separation symbol could not be found
                 Unexpected data found.
                 A two digit second could not be found",
      "file":"\/var\/www\/html\...vendor\/nesbot\/carbon\/src\/Carbon\/Carbon.php",
      "line":359
   }
}

Here is the code that produced the above error:

$tile = Resource::with('comments, ratings')->where('resources.id', '=', 1)->first();
$created_at = $tile->created_at;
$tile->created_at = $created_at->copy()->tz(Auth::user()->timezone)->format('F j, Y @ g:i A');

If I remove ->format('F j, Y @ g:i A') from the above code, it works fine, but it's not in the format I want. What could the problem be? I have almost identical code elsewhere in my app and it works without error.

UPDATE: Using setToStringFormat('F j, Y @ g:i A') does not cause an error, but returns null.

Answer

chipit24 picture chipit24 · Aug 10, 2014

Adding the following code to my model worked for me:

public function getCreatedAtAttribute($date)
{
    if(Auth::check())
        return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->copy()->tz(Auth::user()->timezone)->format('F j, Y @ g:i A');
    else
        return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->copy()->tz('America/Toronto')->format('F j, Y @ g:i A');
}

public function getUpdatedAtAttribute($date)
{
    return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('F j, Y @ g:i A');
}

This allows me to use created_at and updated_at in the format I want.