Hi Artisan,
In this tutorial, I will explain laravel 9 task scheduling example. I will show you step by step about laravel cron schedule in Laravel 9. In this tutorial, I would like to show you how to set up a task scheduling cron job in laravel 9 application.
To show you how to create cron jobs features in Laravel 9, I will send notifications to all inactive users via cron jobs. If you don't know about cron jobs and want to know how Laravel cron jobs work then this example is perfect for you.
Why do we need cron jobs in our applications? First, we need to be clear about it. We have to know what is a benefit to using cron jobs in laravel 9 and how to set up cron jobs in laravel 9? Many times we need to send something to users automatically after a couple of times or a day or a month. So at that time, there is cron jobs to solve this kind of problem.
In this tutorial, we will first find out our inactive users and send them email notifications to their email addresses using laravel custom command. We will send this notification using laravel task scheduling.
So for making it, we have to add a new field in our user database table, So let's add a new field to our user database table.
Step 1: Setup Table
Now go to the user table and paste this below code to your user table.
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('role')->default('user');
$table->tinyInteger('active')->default(1);
$table->timestamp('last_login')->nullable();
$table->rememberToken();
$table->timestamps();
});
Now after adding it run migrate command to add this field. See here we add the last_login
field to check when was the user last logged in.
Step 2: Create Custom Command
For creating our custom command, run this below command
php artisan make:command ourCustomCommandName
php artisan make:command inactive-users
After running this command you will see this file to this following directory app\Console\Commands\EmailInactiveUsers.php.
Step 3: Setup EmailInactiveUsers.php
Open app\Console\Commands\EmailInactiveUsers.php and paste the following code.
Read more : Binding Data to Views Using View Composers in Laravel
app\Console\Commands\EmailInactiveUsers.php
namespace App\Console\Commands;
use App\Notifications\NotifyInactiveUser;
use Carbon\Carbon;
use Illuminate\Console\Command;
class EmailInactiveUsers extends Command
{
protected $signature = 'command:name';
protected $description = 'command description';
public function __construct()
{
parent::__construct();
}
public function handle()
{
//Logic goes here
}
}
Now see protected $signature = 'command:name'; this should be our custom command name and In handle() method , we have to setup our logic.
Step 4: Make Notification
Run this command to make new notification
php artisan make:notification NotifyInactiveUser
After running this command you will see this file to the following directory app\Notifications\NotifyInactiveUser.php
and paste this below code
app\Notifications\NotifyInactiveUser.php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class NotifyInactiveUser extends Notification
{
use Queueable;
public function __construct()
{
//
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->line('You are not using our website for a long time')
->action('Please login again', route('login'))
->line('Thank you for joining our codechief community!');
}
public function toArray($notifiable)
{
return [
//
];
}
}
Step 5: Setup EmailInactiveUsers.php
Open app\Console\Commands\EmailInactiveUsers.php and paste the following code.
app\Console\Commands\EmailInactiveUsers.php
namespace App\Console\Commands;
use App\Notifications\NotifyInactiveUser;
use Carbon\Carbon;
use Illuminate\Console\Command;
class EmailInactiveUsers extends Command
{
protected $signature = 'email:inactive-users';
protected $description = 'Email inactive users';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$limit = Carbon::now()->subDay(7);
$inactive_user = User::where('last_login', '<', $limit)->get();
foreach ($inactive_user as $user) {
$user->notify(new NotifyInactiveUser());
}
}
}
Now if you run php artisan
then you can see our custom command in laravel artisan command list.
Here we use this $limit = Carbon::now()->subDay(7); statement to get who logged in 7 days before and then send them notification.
Step 6: Setup Auth Controller
To save last_login
field data, go to your login mechanism and paste this below code to your login attempt method.
$user = auth()->user();
$user->last_login = Carbon::now();
$user->save();
See here we've saved the current time when a user is going to log in.
Step 7: Register Our Custom Command
To register our custom command, go to app\Console\Kernel.php. In Kernel.php
, register our command class inside $commands
array.
app\Console\Kernel.php
EmailInactiveUsers::class,
and paste this code to control the schedule.
$schedule->command('email:inactive-users')
->weekly();
Looking at the schedule
method, we can define how many times later we want to process our schedule. To know more you can visit the below links.
So our ultimate Kernel.php will look like this
namespace App\Console;
use App\Console\Commands\EmailInactiveUsers;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
EmailInactiveUsers::class,
];
protected function schedule(Schedule $schedule)
{
$schedule->command('email:inactive-users')
->weekly();
}
protected function commands()
{
$this->load(__DIR__ . '/Commands');
require base_path('routes/console.php');
}
}
Now if you run
php artisan email:inactive-users
Then our logic will work. That means our notification will be sent to that user who logged in 7 days ago. hope you got it.
Step 8: Run Scheduler Command
now we are ready to run our cron, so you can manually check using the following command of your cron. so let's run bellow command:
php artisan schedule:run
Cron Job Setup on Server
At last, you can manage this command on scheduling tasks, you have to add a single entry to your server’s crontab file:
* * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1
OR
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Read also: Vuex Complete Guide with Axios Api Call in Vue Js
I hope it can help you.
#laravel #laravel-9x #cron-jobs