Home >Backend Development >PHP Tutorial >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 IlluminateDatabaseEloquentPrunable 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.
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)); } }
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.
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();
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.
The above is the detailed content of Prunable Eloquent Models. For more information, please follow other related articles on the PHP Chinese website!