Today's Laravel release (8.50.0) includes support for "prunable" and "mass prunable" models. You will notice that sometimes you may want to periodically delete models that are no longer needed. In this example i will discuss about Laravel prunable model and when to use and how to declare prunable model.
In this type of situation you may add the Illuminate\Database\Eloquent\Prunable
or Illuminate\Database\Eloquent\MassPrunable
trait to the models you would like to periodically prune.
After adding the traits to the model, implement a prunable
method which returns an Eloquent query builder that resolves the models that are no longer needed like below:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;
class Flight extends Model
{
use Prunable;
/**
* Get the prunable model query.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function prunable()
{
return static::where('created_at', '<=', now()->subMonth());
}
}
When marking models as Prunable
, we can also add a pruning
method in this model. Remember
this pruning
method will be called before the model is deleted. This pruning
method can be useful to delete any additional resources associated with the model
/**
* Prepare the model for pruning.
*
* @return void
*/
protected function pruning()
{
//
}
After configuring our prunable model, we should schedule the model:prune
Artisan command in your application's App\Console\Kernel
class.
App\Console\Kernel
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('model:prune')->daily();
}
Now after adding the scheduler behind the scenes, the model:prune
command will automatically detect "Prunable" models within app/Models
directory.
If our models are in a different location, you may use the --model
option to specify the model class names:
$schedule->command('model:prune', [
'--model' => [Address::class, Flight::class],
])->daily();
Read also: How to Copy File from One Folder to Another in Laravel
Hope it can help you.
#laravel #laravel-8x