How to delete some records or files after X time - Laravel 5

Viewed 7819

I want to create a script, to delete some records after X time, I will choose it, but I don't know, How can I do that? And the same thing with my files, I want to delete some files after X time from upload for example, and to do that, I will delete the file from my storage, and the file record from the database, but that will make my site slow, Any way to do that without problems

Use this for example?

Soft Deleting or Task Scheduling

My Table is: My Table Image so I want to delete this record for example after 2 hours from creation? but I have a lot of records? how to do that?

Files Table : Files Table Part 1 Files Table Part 2 these are my records, they contain the path of my files, but every file will expire after 5 days from creation for example, so I will delete it from the path and delete there record from the database after that. but that will make the site very slow? any way to do that?

Thanks :)

2 Answers
Files::where('created_at', '<', Carbon::now()->subHours(2))->delete();

Make sure you have the Carbon package installed

Laravel handles this quite well. You were correct, use the Task Scheduler

What I would recommend would be to set up two different jobs, because you have two different criteria (2 hours, 5 days) for the time between tasks.

For the records, you can set up a check within your job to see when the record was created, and delete those that are more than 2 hours old. Something like:

$schedule->call(function () {
        DB::table('your_table')->whereRaw('created_at >= now() - interval 2 hour')
    })->daily();

If you use Carbon, you can change the query around using something like:

->where('created_at', '>=', Carbon::now()->subMinutes(120)->toDateTimeString());

Same thing with the file deletion - make a job that deletes those files older than 5 days. It won't slow your system much if you set the job to go off maybe once a day at your least popular times. So, when making your job:

$schedule->job(new YourJob)->dailyAt('3:00');

There are a lot of ways to do this. But, you'll need to learn how the scheduler works (easy) and then you can employ the possible solutions here.

Related