Automatically remove records using Prunable trait in Laravel

You can use the Prunable trait to automatically remove models (records) from your database. For example, you can permanently remove soft deleted models after a few days using prunable traits in Laravel.

Answers 1
  • Add Prunable trait to the model to remove soft deleted records permanently after a few days

    --PATH app\Models\Post.php
    <?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Prunable;
    use Illuminate\Database\Eloquent\SoftDeletes;
    
    class Post extends Model
    {
        use SoftDeletes;
    
        use Prunable; 
    
        /**
         * Determines the prunable query.
         *
         * @return \Illuminate\Database\Eloquent\Builder
         */
        public function prunable()
        {
            return $this->where('created_at', '<=', now()->subDays(15));
        }
    }
    
    //Add PruneCommand to your schedule
    //app/Console/Kernel.php
    $schedule->command(PruneCommand::class)->daily();
    
    0

    Sometimes you have to delete the records from tables which are soft deleted and you want to remove it permanently from the table in that case you can use prunable traits.

  • Back to code snippet queries related laravel