Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Allow modifiers in date format #34507

Merged
merged 6 commits into from
Sep 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
}

/**
Expand Down
28 changes: 28 additions & 0 deletions tests/Database/DatabaseEloquentIntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down