Reputation: 71
I want to create a cron job which fires off a task/command in Laravel to remove all records which are 1 week old. I am trying to use ExpressiveDate to help me out to evaluate the time. What is the best way in Laravel to do this?
I have registered the command:
Artisan::add(new removeWeek);
And created a removeWeek.php command under /apps/command and that works fine. I am looking for the best syntax -an eloquent way- to traverse my records and only remove records a week old from the current day. The cron job will run once a day.
Upvotes: 1
Views: 1286
Reputation: 25782
The laravel way to remove records periodically is by using the trait Illuminate\Database\Eloquent\Prunable
This will help you to delete models that are no longer needed by implementing the prunable
method which returns an Eloquent query builder that resolves the models to remove.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;
class Post extends Model
{
use Prunable;
/**
* Get the prunable model query.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function prunable()
{
return static::where('created_at', '<=', now()-> subWeek());
}
}
Then run the command:
php artisan model:prune
Of course you can schedule the model:prune
artisan command to run periodically
Here is the link for documentation: https://laravel.com/docs/8.x/eloquent#pruning-models
Upvotes: 4
Reputation: 87719
Looks like you have all set, so now you just have to
Calendar::where('created_at', '<', \Carbon\Carbon::now()->subWeek())->delete();
One last thing: classes names are conventionally Capitalized:
class RemoveWeek() {
}
Upvotes: 2