MassPrunable.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. namespace Illuminate\Database\Eloquent;
  3. use Illuminate\Database\Events\ModelsPruned;
  4. use LogicException;
  5. trait MassPrunable
  6. {
  7. /**
  8. * Prune all prunable models in the database.
  9. *
  10. * @param int $chunkSize
  11. * @return int
  12. */
  13. public function pruneAll(int $chunkSize = 1000)
  14. {
  15. $query = tap($this->prunable(), function ($query) use ($chunkSize) {
  16. $query->when(! $query->getQuery()->limit, function ($query) use ($chunkSize) {
  17. $query->limit($chunkSize);
  18. });
  19. });
  20. $total = 0;
  21. do {
  22. $total += $count = in_array(SoftDeletes::class, class_uses_recursive(get_class($this)))
  23. ? $query->forceDelete()
  24. : $query->delete();
  25. if ($count > 0) {
  26. event(new ModelsPruned(static::class, $total));
  27. }
  28. } while ($count > 0);
  29. return $total;
  30. }
  31. /**
  32. * Get the prunable model query.
  33. *
  34. * @return \Illuminate\Database\Eloquent\Builder
  35. */
  36. public function prunable()
  37. {
  38. throw new LogicException('Please implement the prunable method on your model.');
  39. }
  40. }