How to automatically delete database record using Laravel?

2.3k views Asked by At

I have a table named, for example, "posts". What I need, is to automatically delete a specific post record from DB which was not updated for 1 week. What would be the optimal way to achieve it?

1

There are 1 answers

0
kerrin On BEST ANSWER

Look in to Queues - https://laravel.com/docs/5.5/queues

You would generate a job every hour (for example) that checks if there are any posts with an updated_at timestamp of greater than one week. Loop through these and delete.

Example:

$stale_posts = Posts::where('updated_at', '<', Carbon::now()->subDays(7))->get();

foreach ($stale_posts as $post) {
    $post->delete();
}