In this episode, we dive into how to schedule actions on Eloquent models in Laravel with super high accuracy. We walk through a real-world example—scheduling user deletions at a particular date and time—and look at how you could do the same for anything else, like publishing blog posts or other time-based tasks.
First, we set up a fresh Laravel project, tweak the database, and add a deletes_at
column to the users table. Then, we create some fake users to play with. Next, we make a console command that checks for any users scheduled for deletion (where deletes_at
is in the past) and deletes them. Pretty simple!
But, of course, we don't want to have to run this manually all the time. We want to automate it. By default, Laravel's scheduler only works every minute, but sometimes you need more precision. That's why we pull in the laravel-short-schedule
package, which makes it possible to run the command every second. Now, we can have actions happen almost exactly when we want.
To make things more efficient and scalable, instead of deleting users right in the command, we move that logic into a queued job. This way, if you have lots of users (or any other model) scheduled for an action at once, Laravel can process them in the background without freezing up your app.
We also cover an important gotcha: if you schedule the job every second, it's easy to end up with duplicate jobs for the same model. To solve this, we use Laravel's ShouldBeUnique
interface and give each job a unique id, so only one job per user is queued at a time.
By the end of this episode, you'll have a solid approach for reliably scheduling any kind of action on your models in Laravel, whether you need second-level accuracy or just want to queue up something to happen in the background later on.