master

laravel/framework

Last updated at: 29/12/2023 09:22

MassPrunable.php

TLDR

This file contains a trait called MassPrunable, which provides two methods for pruning (deleting) prunable models from the database. The main method is pruneAll, which prunes all prunable models in the database. The second method is prunable, which should be implemented by the model using this trait to define the query for selecting prunable models.

Methods

pruneAll(int $chunkSize = 1000): int

This method prunes all prunable models in the database. It takes an optional parameter $chunkSize to specify the number of models to prune in each iteration (defaults to 1000). The method uses the prunable method to construct the query for selecting prunable models. It then continuously prunes the models in chunks until no more models are pruned. Returns the total number of pruned models.

prunable(): \Illuminate\Database\Eloquent\Builder

This method should be implemented by the model using the MassPrunable trait. It should return an instance of the Builder class from the Eloquent package, representing the query for selecting prunable models. If this method is not implemented, a LogicException will be thrown.

<?php

namespace Illuminate\Database\Eloquent;

use Illuminate\Database\Events\ModelsPruned;
use LogicException;

trait MassPrunable
{
    /**
     * Prune all prunable models in the database.
     *
     * @param  int  $chunkSize
     * @return int
     */
    public function pruneAll(int $chunkSize = 1000)
    {
        $query = tap($this->prunable(), function ($query) use ($chunkSize) {
            $query->when(! $query->getQuery()->limit, function ($query) use ($chunkSize) {
                $query->limit($chunkSize);
            });
        });

        $total = 0;

        do {
            $total += $count = in_array(SoftDeletes::class, class_uses_recursive(get_class($this)))
                        ? $query->forceDelete()
                        : $query->delete();

            if ($count > 0) {
                event(new ModelsPruned(static::class, $total));
            }
        } while ($count > 0);

        return $total;
    }

    /**
     * Get the prunable model query.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function prunable()
    {
        throw new LogicException('Please implement the prunable method on your model.');
    }
}