diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php index 498e87195adc..655f1018a504 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php @@ -14,6 +14,7 @@ use Illuminate\Support\Collection as BaseCollection; use Illuminate\Support\Facades\Date; use Illuminate\Support\Str; +use InvalidArgumentException; use LogicException; trait HasAttributes @@ -912,11 +913,13 @@ protected function asDateTime($value) // Finally, we will just assume this date is in the format used by default on // the database connection and use that format to create the Carbon object // that is returned back out to the developers after we convert it here. - if (Date::hasFormat($value, $format)) { - return Date::createFromFormat($format, $value); + try { + $date = Date::createFromFormat($format, $value); + } catch (InvalidArgumentException $e) { + $date = false; } - return Date::parse($value); + return $date ?: Date::parse($value); } /** diff --git a/tests/Database/DatabaseEloquentIntegrationTest.php b/tests/Database/DatabaseEloquentIntegrationTest.php index db36f33c6ccc..bf304590b83b 100644 --- a/tests/Database/DatabaseEloquentIntegrationTest.php +++ b/tests/Database/DatabaseEloquentIntegrationTest.php @@ -1413,6 +1413,34 @@ public function testTimestampsUsingOldSqlServerDateFormatFallbackToDefaultParsin $this->assertFalse(Date::hasFormat('2017-11-14 08:23:19.734', $model->getDateFormat())); } + public function testSpecialFormats() + { + $model = new EloquentTestUser; + $model->setDateFormat('!Y-d-m \\Y'); + $model->setRawAttributes([ + 'updated_at' => '2017-05-11 Y', + ]); + + $date = $model->getAttribute('updated_at'); + $this->assertSame('2017-11-05 00:00:00.000000', $date->format('Y-m-d H:i:s.u'), 'the date should respect the whole format'); + + $model->setDateFormat('Y d m|'); + $model->setRawAttributes([ + 'updated_at' => '2020 11 09', + ]); + + $date = $model->getAttribute('updated_at'); + $this->assertSame('2020-09-11 00:00:00.000000', $date->format('Y-m-d H:i:s.u'), 'the date should respect the whole format'); + + $model->setDateFormat('Y d m|*'); + $model->setRawAttributes([ + 'updated_at' => '2020 11 09 foo', + ]); + + $date = $model->getAttribute('updated_at'); + $this->assertSame('2020-09-11 00:00:00.000000', $date->format('Y-m-d H:i:s.u'), 'the date should respect the whole format'); + } + public function testUpdatingChildModelTouchesParent() { $before = Carbon::now();