1 | <?php |
||
8 | trait CascadeSoftDeletes |
||
9 | { |
||
10 | /** |
||
11 | * Boot the trait. |
||
12 | * |
||
13 | * Listen for the deleting event of a soft deleting model, and run |
||
14 | * the delete operation for any configured relationship methods. |
||
15 | * |
||
16 | * @throws \LogicException |
||
17 | */ |
||
18 | 6 | protected static function bootCascadeSoftDeletes() |
|
19 | { |
||
20 | static::deleting(function ($model) { |
||
21 | 6 | if (! $model->implementsSoftDeletes()) { |
|
22 | 1 | throw new LogicException(sprintf( |
|
23 | 1 | '%s does not implement Illuminate\Database\Eloquent\SoftDeletes', |
|
24 | get_called_class() |
||
25 | )); |
||
26 | } |
||
27 | |||
28 | 5 | if ($invalidCascadingRelationships = $model->hasInvalidCascadingRelationships()) { |
|
29 | 3 | throw new LogicException(sprintf( |
|
30 | 3 | '%s [%s] must exist and return an object of type Illuminate\Database\Eloquent\Relations\Relation', |
|
31 | 3 | str_plural('Relationship', count($invalidCascadingRelationships)), |
|
32 | 3 | join(', ', $invalidCascadingRelationships) |
|
33 | )); |
||
34 | } |
||
35 | |||
36 | 2 | foreach ($model->getCascadingDeletes() as $relationship) { |
|
37 | 2 | $model->{$relationship}()->delete(); |
|
38 | } |
||
39 | 5 | }); |
|
40 | 5 | } |
|
41 | |||
42 | |||
43 | /** |
||
44 | * Determine if the current model implements soft deletes. |
||
45 | * |
||
46 | * @return bool |
||
47 | */ |
||
48 | 6 | protected function implementsSoftDeletes() |
|
52 | |||
53 | |||
54 | /** |
||
55 | * Determine if the current model has any invalid cascading relationships defined. |
||
56 | * |
||
57 | * A relationship is considered invalid when the method does not exist, or the relationship |
||
58 | * method does not return an instance of Illuminate\Database\Eloquent\Relations\Relation. |
||
59 | * |
||
60 | * @return array |
||
61 | */ |
||
62 | protected function hasInvalidCascadingRelationships() |
||
68 | |||
69 | |||
70 | /** |
||
71 | * Fetch the defined cascading soft deletes for this model. |
||
72 | * |
||
73 | * @return array |
||
74 | */ |
||
75 | 5 | protected function getCascadingDeletes() |
|
79 | } |
||
80 |