From a227fc9831731e51f4777de7e485323b240e0814 Mon Sep 17 00:00:00 2001 From: Brian Dillingham <brian@dillingham.dev> Date: Tue, 19 Oct 2021 14:43:19 -0400 Subject: [PATCH] wip --- README.md | 15 ++++++++++++--- src/SoftDeletesParent.php | 8 ++++++-- tests/TestCase.php | 4 ++++ 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 419b48f..6cb655d 100644 --- a/README.md +++ b/README.md @@ -32,18 +32,27 @@ And add the trait and parent model to your child model: namespace App\Models; -use App\Models\Author; use Dillingham\SoftDeletesParent\SoftDeletesParent; use Illuminate\Database\Eloquent\Model; class Post extends Model { use SoftDeletesParent; - - protected static $softDeletesParent = Author::class; } ``` +```php +<?php + +namespace App\Providers; +class AppServiceProvider +{ + public function register() + { + Post::softDeletesParent(Author::class); + } +} +``` ### Scopes diff --git a/src/SoftDeletesParent.php b/src/SoftDeletesParent.php index 1aae369..779706e 100755 --- a/src/SoftDeletesParent.php +++ b/src/SoftDeletesParent.php @@ -4,20 +4,24 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\Event; trait SoftDeletesParent { protected static function bootSoftDeletesParent() { static::addGlobalScope(new SoftDeletesParentScope()); + } - static::$dispatcher->listen('eloquent.deleting: '. static::$softDeletesParent, function (Model $model) { + public static function softDeletesParent($parent) + { + Event::listen('eloquent.deleting: '. $parent, function (Model $model) { static::query()->where([ $model->getForeignKey() => $model->getKey(), ])->update(['parent_deleted_at' => now()]); }); - static::$dispatcher->listen('eloquent.restoring: '. static::$softDeletesParent, function ($model) { + Event::listen('eloquent.restoring: '. $parent, function (Model $model) { static::query()->withParentTrashed()->where([ $model->getForeignKey() => $model->getKey(), ])->update(['parent_deleted_at' => null]); diff --git a/tests/TestCase.php b/tests/TestCase.php index db50384..8b66397 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -3,6 +3,8 @@ namespace Dillingham\SoftDeletesParent\Tests; use Dillingham\SoftDeletesParent\SoftDeletesParentServiceProvider; +use Dillingham\SoftDeletesParent\Tests\Fixtures\Author; +use Dillingham\SoftDeletesParent\Tests\Fixtures\Post; use Illuminate\Database\Eloquent\Model; use Orchestra\Testbench\TestCase as Orchestra; @@ -19,6 +21,8 @@ public function getEnvironmentSetUp($app) { Model::unguard(); + Post::softDeletesParent(Author::class); + config()->set('database.default', 'testing'); $migration = include __DIR__ . '/Fixtures/Database/create_authors_table.php.stub';