Automatically remove records using Prunable trait in Laravel

Created at 10-Jan-2022 , By samar

Automatically remove records using Prunable trait in Laravel

Through the use of the programming language, we will work together to solve the "Automatically remove records using Prunable trait in Laravel" puzzle in this lesson.

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.
  • 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();
    

    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

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.