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

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.


I did experience the same problem, and in my search for an answer I stumled across How do you explain the result for a new \DateTime('0000-00-00 00:00:00')? .

I decided to change the datetime-columns in the database to nullable with default value = NULL, to prevent fields from having value '0000-00-00 00:00:00'.

My migration in laravel 5 looks like this:

Schema::table('table', function($table)
{
    $table->dateTime('created_at')->nullable()->default(null)->change();
    $table->dateTime('updated_at')->nullable()->default(null)->change();
});

It's not a carbon issue, it's a conflict between a setAttribute or getAttribute in your model.