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.
-
Add the
MassPrunabletrait and aprunable()method toPost. UsePrunableinstead if you need Eloquent model events to fire during deletion.Modules/Blog/app/Models/Post.php <?phpnamespace 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());}} -
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)]);" -
Preview what will be deleted with
--pretend(deletes nothing).Terminal window php artisan module:prune Blog --pretendINFO 2 [Modules\Blog\Models\Post] records will be pruned. -
Prune the records.
Terminal window php artisan module:prune BlogINFO Pruning [Modules\Blog\Models\Post] records.Modules\Blog\Models\Post ......................................... 2 records -
Check the result by running
--pretendagain.Terminal window php artisan module:prune Blog --pretendThe output reports
No prunable [Modules\Blog\Models\Post] records found.
Prune on a schedule
Section titled “Prune on a schedule”Uncomment configureSchedules() in your module service provider to run module:prune daily (see Schedule tasks from a module):
protected function configureSchedules(Schedule $schedule): void{ $schedule->command('module:prune', ['Blog'])->daily();}Verify with php artisan schedule:list.
Prune several modules or specific models
Section titled “Prune several modules or specific models”Pass --all to prune every enabled module. Use repeatable --model or --except flags (not both together) to include or exclude specific models:
php artisan module:prune --allphp artisan module:prune Blog --model=Postphp artisan module:prune Blog --except=PostShort 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.