Skip to content

Commit

Permalink
Merge pull request #39 from tonysm/tm/model-touching
Browse files Browse the repository at this point in the history
Model Touching
  • Loading branch information
tonysm authored Feb 19, 2024
2 parents 3133f1f + b758fa3 commit 5ef7912
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/Models/Traits/HasRichText.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,16 @@ protected static function bootHasRichText()
static::registerRichTextRelationships($field);
}

static::saving(function (Model $model) {
foreach ($model->getRichTextFields() as $field) {
$relationship = static::fieldToRichTextRelationship($field);

if ($model->relationLoaded($relationship) && $model->{$field}->isDirty() && $model->timestamps) {
$model->updateTimestamps();
}
}
});

static::saved(function (Model $model) {
foreach ($model->getRichTextFields() as $field) {
$relationship = static::fieldToRichTextRelationship($field);
Expand Down
36 changes: 36 additions & 0 deletions tests/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,40 @@ public function updates_content()

HTML, "{$post->refresh()->body}");
}

/** @test */
public function touches_record_when_rich_text_is_updated()
{
$this->freezeTime();

$post = PostFactory::new()->create([
'body' => '<h1>Old Value</h1>',
])->fresh();

$this->travel(5)->minutes();

$post->update([
'body' => '<h1>New Value</h1>',
]);

$this->assertFalse($post->created_at->eq($post->updated_at), 'Didnt touch the record timestamps.');
}

/** @test */
public function doesnt_touch_record_when_rich_text_isnt_updated()
{
$this->freezeTime();

$post = PostFactory::new()->create([
'body' => '<h1>Old Value</h1>',
])->fresh();

$this->travel(5)->minutes();

$post->update([
'body' => '<h1>Old Value</h1>',
]);

$this->assertTrue($post->created_at->eq($post->updated_at), 'Record timestamps were touched, but it shouldnt.');
}
}
2 changes: 1 addition & 1 deletion workbench/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ APP_KEY=AckfSECXIvnK5r28GVIWUAxmbBSjTsmF
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack
LOG_CHANNEL=stderr
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

Expand Down

0 comments on commit 5ef7912

Please sign in to comment.