Skip to content

Commit

Permalink
fix nullable dates
Browse files Browse the repository at this point in the history
  • Loading branch information
Gummibeer committed May 29, 2019
1 parent 50d20d2 commit 39a65e3
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
13 changes: 9 additions & 4 deletions src/Traits/DetectsChanges.php
Expand Up @@ -121,12 +121,17 @@ public static function logChanges(Model $model): array
foreach ($attributes as $attribute) {
if (Str::contains($attribute, '.')) {
$changes += self::getRelatedModelAttributeValue($model, $attribute);
} elseif (in_array($attribute, $model->getDates())) {
$changes[$attribute] = $model->serializeDate(
$model->asDateTime($model->getAttribute($attribute))
);
} else {
$changes[$attribute] = $model->getAttribute($attribute);

if (
in_array($attribute, $model->getDates())
&& ! is_null($changes[$attribute])
) {
$changes[$attribute] = $model->serializeDate(
$model->asDateTime($changes[$attribute])
);
}
}
}

Expand Down
30 changes: 30 additions & 0 deletions tests/DetectsChangesTest.php
Expand Up @@ -902,6 +902,36 @@ public function setAttribute($key, $value)
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
}

/** @test */
public function it_can_use_nullable_date_as_loggable_attributes()
{
$userClass = new class() extends User {
protected $fillable = ['name', 'text'];
protected static $logAttributes = ['*'];

use LogsActivity, SoftDeletes;
};

Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0));
$user = new $userClass();
$user->name = 'my name';
$user->text = 'my text';
$user->save();

$expectedChanges = [
'attributes' => [
'id' => $user->getKey(),
'name' => 'my name',
'text' => 'my text',
'created_at' => '2017-01-01 12:00:00',
'updated_at' => '2017-01-01 12:00:00',
'deleted_at' => null,
],
];

$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
}

protected function createArticle(): Article
{
$article = new $this->article();
Expand Down

0 comments on commit 39a65e3

Please sign in to comment.