diff --git a/README.md b/README.md index 0219a0d..608e5ae 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,12 @@ $post->publish(); // Unpublish the post $post->unpublish(); + +// Publish the post without firing model events +$post->publishQuietly(); + +// Unpublish the post without firing model events +$post->unpublishQuietly(); ``` A post is considered published when the `published_at` is not null and in the past. diff --git a/src/Publishable.php b/src/Publishable.php index 8c2cd71..a45bc82 100644 --- a/src/Publishable.php +++ b/src/Publishable.php @@ -6,7 +6,7 @@ use Illuminate\Database\Eloquent\Builder; trait Publishable -{ +{ /** * Scope a query to only include published models. * @@ -59,6 +59,18 @@ public function publish() return $this->save(); } + /** + * Publishes the model without firing events. + * + * @return bool + */ + public function publishQuietly() + { + $this->published_at = Carbon::now(); + + return $this->saveQuietly(); + } + /** * @return bool */ @@ -69,6 +81,18 @@ public function unpublish() return $this->save(); } + /** + * Unpublishes the model without firing events. + * + * @return bool + */ + public function unpublishQuietly() + { + $this->published_at = null; + + return $this->saveQuietly(); + } + /** * @param mixed $value * @return \Carbon\Carbon diff --git a/tests/PublishableTest.php b/tests/PublishableTest.php index 74f7574..2ee463a 100644 --- a/tests/PublishableTest.php +++ b/tests/PublishableTest.php @@ -3,6 +3,7 @@ namespace PawelMysior\Publishable\Tests; use Carbon\Carbon; +use Illuminate\Support\Facades\Event; class PublishableTest extends TestCase { @@ -132,4 +133,44 @@ public function test_published_at_field_is_not_fillable() $post = new Post(); $this->assertNotContains('published_at', $post->getFillable()); } + + /** + * @test + */ + public function test_publish_quietly_function_does_not_fire_model_events() + { + // Fake events so we can test on them. + Event::fake(); + + // Create a post. + $post = Post::create([ + 'published_at' => Carbon::yesterday(), + ]); + + // Run publish Quietly Function. + $post->publishQuietly(); + + // Assert it doesn't trigger the updated event. + Event::assertNotDispatched('eloquent.updated: PawelMysior\Publishable\Tests\Post'); + } + + /** + * @test + */ + public function test_unpublish_quietly_function_does_not_fire_model_events() + { + // Fake events so we can test on them. + Event::fake(); + + // Create a post. + $post = Post::create([ + 'published_at' => Carbon::yesterday(), + ]); + + // Run publish Quietly Function. + $post->unpublishQuietly(); + + // Assert it doesn't trigger the updated event. + Event::assertNotDispatched('eloquent.updated: PawelMysior\Publishable\Tests\Post'); + } }