master

laravel/framework

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

Prunable.php

TLDR

This file is a trait called Prunable that can be used in Laravel's Eloquent models. It provides methods to prune (delete) models from the database.

Methods

pruneAll

This method prunes all prunable models in the database. It takes an optional parameter chunkSize to specify the number of models to process at a time. The method iterates over the models in chunks, calls the prune method on each model, and fires a ModelsPruned event with the total count of pruned models.

prunable

This method returns the prunable model query. It is expected to be implemented in the model that uses the Prunable trait. If this method is not implemented, a LogicException will be thrown.

prune

This method prunes (deletes) the model from the database. It first calls the pruning method, then checks if the model uses the SoftDeletes trait. If it does, the model is force deleted, otherwise it is deleted normally.

pruning

This protected method is called before the model is pruned. It can be overridden in the model to perform any necessary preparation.

<?php

namespace Illuminate\Database\Eloquent;

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

trait Prunable
{
    /**
     * Prune all prunable models in the database.
     *
     * @param  int  $chunkSize
     * @return int
     */
    public function pruneAll(int $chunkSize = 1000)
    {
        $total = 0;

        $this->prunable()
            ->when(in_array(SoftDeletes::class, class_uses_recursive(get_class($this))), function ($query) {
                $query->withTrashed();
            })->chunkById($chunkSize, function ($models) use (&$total) {
                $models->each->prune();

                $total += $models->count();

                event(new ModelsPruned(static::class, $total));
            });

        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.');
    }

    /**
     * Prune the model in the database.
     *
     * @return bool|null
     */
    public function prune()
    {
        $this->pruning();

        return in_array(SoftDeletes::class, class_uses_recursive(get_class($this)))
                ? $this->forceDelete()
                : $this->delete();
    }

    /**
     * Prepare the model for pruning.
     *
     * @return void
     */
    protected function pruning()
    {
        //
    }
}