DEV Community

Paulund
Paulund

Posted on • Originally published at paulund.co.uk

1

Prunable Eloquent Models

Since Laravel 8.5 there was a trait added to the framework that will allow you to prune models based on a date. This
trait is called Illuminate\Database\Eloquent\Prunable and it will allow you to prune models based on a date.

This trait is useful when you have models that you want to delete based on a date. For example, you might have a model
that stores logs and you want to delete logs that are older than a certain date.

In this article, we're going to look at how you can create a trait that will allow you to prune models based on a date.

Using the Prunable Trait

To use the Prunable trait you need to add it to your model and define a prunable method that will return a query
builder instance. This query builder instance will be used to prune the models based on a date.

Here's an example of how you can use the Prunable trait in a model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;

class Log extends Model
{
    use Prunable;

    public function prunable()
    {
        return $this->where('created_at', '<', now()->subDays(30));
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we have a Log model that uses the Prunable trait. We have defined a prunable method that returns
a query builder instance that will delete logs that are older than 30 days.

Schedule Pruning

To prune the models you need to schedule the pruning to run at a certain time. You can do this by adding a command
to your routes/console.php file that will call the prune method on the model.

Here's an example of how you can schedule the pruning of the Log model:

<?php

use Illuminate\Support\Facades\Schedule;

Schedule::command('model:prune')->daily();
Enter fullscreen mode Exit fullscreen mode

In this example, we're scheduling the model:prune command to run daily. This command will call the prune method
on the Log model and delete logs that are older than 30 days.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more