DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Laravel 9 - Prunable trait to automatically remove models from your database
Sandro Jhuliano Cagara
Sandro Jhuliano Cagara

Posted on

Laravel 9 - Prunable trait to automatically remove models from your database

You can use the Prunable trait to automatically remove models from your database.

(ex.) You can permanently remove soft deleted models after a few days.

class ExampleClass extends Model
{
    use SoftDeletes;
    use Prunable;

    public function prunable()
    {
        // Files matching this query will be pruned
        return static::query()->where('deleted_at', '<=', now()->subDays(14));
    }

    protected function pruning()
    {
        // Remove the file from s3 before deleting the model
        Storage::disk('s3')->delete($this->filename);
    }
}
Enter fullscreen mode Exit fullscreen mode

Add PruneCommand to your schedule (app/Console/Kernel.php)

$schedule->command(PruneCommand::class)->daily();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

What image format should you use in your next project? πŸ€”