Skip to content

Prune module models

To delete Post records in the Blog module older than a year, make Post prunable and run module:prune. You need the Post model and PostFactory from Add Eloquent models to a module.

Laravel’s model:prune scans application models only. module:prune wraps it to find models inside modules.

  1. Add the MassPrunable trait and a prunable() method to Post. Use Prunable instead if you need Eloquent model events to fire during deletion.

    Modules/Blog/app/Models/Post.php
    <?php
    namespace Modules\Blog\Models;
    use Illuminate\Database\Eloquent\Attributes\UseFactory;
    use Illuminate\Database\Eloquent\Builder;
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\MassPrunable;
    use Illuminate\Database\Eloquent\Model;
    use Modules\Blog\Database\Factories\PostFactory;
    #[UseFactory(PostFactory::class)]
    class Post extends Model
    {
    /** @use HasFactory<PostFactory> */
    use HasFactory, MassPrunable;
    protected $fillable = ['title', 'body'];
    public function prunable(): Builder
    {
    return static::where('created_at', '<=', now()->subYear());
    }
    }
  2. Create two old posts to test pruning.

    Terminal window
    php artisan tinker --execute="Modules\Blog\Models\Post::factory()->count(2)->create(['created_at' => now()->subYears(2)]);"
  3. Preview what will be deleted with --pretend (deletes nothing).

    Terminal window
    php artisan module:prune Blog --pretend
    INFO 2 [Modules\Blog\Models\Post] records will be pruned.
  4. Prune the records.

    Terminal window
    php artisan module:prune Blog
    INFO Pruning [Modules\Blog\Models\Post] records.
    Modules\Blog\Models\Post ......................................... 2 records
  5. Check the result by running --pretend again.

    Terminal window
    php artisan module:prune Blog --pretend

    The output reports No prunable [Modules\Blog\Models\Post] records found.

Uncomment configureSchedules() in your module service provider to run module:prune daily (see Schedule tasks from a module):

Modules/Blog/app/Providers/BlogServiceProvider.php
protected function configureSchedules(Schedule $schedule): void
{
$schedule->command('module:prune', ['Blog'])->daily();
}

Verify with php artisan schedule:list.

Pass --all to prune every enabled module. Use repeatable --model or --except flags (not both together) to include or exclude specific models:

Terminal window
php artisan module:prune --all
php artisan module:prune Blog --model=Post
php artisan module:prune Blog --except=Post

Short names (including sub-folders like Archive/Post) match across all selected modules; fully qualified class names also work. Passing a model name that matches nothing exits with 1 and prunes nothing.