Scheduling Actions on Models In Laravel
One of the most important things in a web application is scheduling actions on models automatically, so we won’t have to worry about logic that varies based on time.
Actions such as account expiration, password change notification and more can be performed automatically and at the right time.
So let’s grab the first example about account expiration and give it a go for scheduling actions on models using Laravel.
By default, Laravel provides us a user migration. We need to add two columns to the users
table migration.
First, let’s add the expired_at
column, which should be of type timestamp
. This column will allow us to determine the expiration date of user accounts.
Second, we should add a status
column with a boolean type. This will give us ability to activate/deactivate user accounts as needed.
So let’s go to user migration file and add these following lines:
$table->timestamp('expired_at')->nullable();
$table->boolean('status')->default(1);
Now we will run:
php artisan migrate
After that, we need to go to user model to write two scope methods, one for getting active
users and another for expired
users:
For automating this action on users, we will run following line to create a Laravel Command:
php artisan make:command HandleUserExpiration
This command will provide us a handle()
method and we can write anything in it.
For disabling expired account we should write these lines:
The last step is scheduling the HandleUserExpiration
command by going to App\Console\Kernel.php
and adding the frequency for automatically running it:
This command will run automatically on background and disable expired user accounts.
We can run it more commonly like: everyMinute()
or rarely like everyDay()
and if there are so many users to deactivate, we can use Laravel lazy loading for better performance and chunking data!
READ MORE: