1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Orkhanahmadov\EloquentRepository\Repository\Concerns; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
6
|
|
|
use Illuminate\Database\Eloquent\Builder; |
7
|
|
|
use Illuminate\Database\Eloquent\Collection; |
8
|
|
|
use Orkhanahmadov\EloquentRepository\Repository\Contracts\Cacheable; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @property-read Builder|Model $model |
12
|
|
|
* @method Builder|Model find(int $modelId) |
13
|
|
|
* @method void invalidateCache() |
14
|
|
|
*/ |
15
|
|
|
trait DeletesEntity |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* Finds a model with ID and deletes it. |
19
|
|
|
* |
20
|
|
|
* @param int|string $modelId |
21
|
|
|
* |
22
|
|
|
* @return bool|mixed|null |
23
|
|
|
* @throws \Exception |
24
|
|
|
*/ |
25
|
|
|
public function findAndDelete($modelId) |
26
|
|
|
{ |
27
|
|
|
$model = $this->find($modelId); |
|
|
|
|
28
|
|
|
|
29
|
|
|
return $this->delete($model); |
|
|
|
|
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Deletes a model. |
34
|
|
|
* |
35
|
|
|
* @param Model $model |
36
|
|
|
* |
37
|
|
|
* @return bool|mixed|null |
38
|
|
|
* @throws \Exception |
39
|
|
|
*/ |
40
|
|
|
public function delete($model) |
41
|
|
|
{ |
42
|
|
|
if ($this instanceof Cacheable) { |
43
|
|
|
$this->invalidateCache($model); |
|
|
|
|
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
return $model->delete(); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Finds a soft deleted model with given ID and restores it. |
51
|
|
|
* |
52
|
|
|
* @param int|string $modelId |
53
|
|
|
* |
54
|
|
|
* @return bool|null |
55
|
|
|
*/ |
56
|
|
|
public function findAndRestore($modelId) |
57
|
|
|
{ |
58
|
|
|
$model = $this->findFromTrashed($modelId); |
59
|
|
|
|
60
|
|
|
return $this->restore($model); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Finds a soft deleted model with given ID. |
65
|
|
|
* |
66
|
|
|
* @param int|string $modelId |
67
|
|
|
* |
68
|
|
|
* @return Builder|Builder[]|Collection|Model|null |
69
|
|
|
*/ |
70
|
|
|
public function findFromTrashed($modelId) |
71
|
|
|
{ |
72
|
|
|
if (! method_exists($this->entity, 'restore')) { |
73
|
|
|
throw new \BadMethodCallException('Model is not using "soft delete" feature.'); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
$model = $this->model->onlyTrashed()->find($modelId); |
77
|
|
|
|
78
|
|
|
if (! $model) { |
79
|
|
|
$this->throwModelNotFoundException($modelId); |
|
|
|
|
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
return $model; |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* Restores soft deleted model. |
87
|
|
|
* |
88
|
|
|
* @param Model $model |
89
|
|
|
* |
90
|
|
|
* @return bool|null |
91
|
|
|
*/ |
92
|
|
|
public function restore($model) |
93
|
|
|
{ |
94
|
|
|
if (! method_exists($this->entity, 'restore')) { |
95
|
|
|
throw new \BadMethodCallException('Model is not using "soft delete" feature.'); |
96
|
|
|
} |
97
|
|
|
|
98
|
|
|
return $model->restore(); |
99
|
|
|
} |
100
|
|
|
} |
101
|
|
|
|