Question

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.

Was it helpful?

Solution

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() {

}

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top