In this tutorial, i would like to show you how to setup task scheduling cron job in laravel 8 application. In this tutorial i will explain about laravel task scheduling and how run cron job.
Laravel provides a convenient way to schedule Cron jobs by scheduling a single schedule:run
Artisan command to be run every minute. The schedule:run
command will examine the job schedule defined in your App\Console\Kernel
class to determine which jobs should be run.
If you don't know how to use laravel cron job and how to use task scheduling in laravel, then you are a right place. This tutorial is for you. In this tutorial we will send email notification to inactive user using task scheduling that mean laravel cron job.
Let's see laravel task scheduling from scratch. Hope you will enjoy it.
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 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 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 app\Console\Commands\EmailInactiveUsers.php
Open app\Console\Commands\EmailInactiveUsers.php and paste the following code.
Read more : Binding Data to Views Using View Composers in Laravel
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 this 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 app\Console\Commands\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 we 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 current time when a user is going to log in.
Step 7: Register Our Custom Command class and Scheduler
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 schedule.
$schedule->command('email:inactive-users')
->weekly();
Look in schedule method, we can define how many time later we want to process our schedule. To know more you can visit below links.
https://laravel.com/docs/7.x/homestead#configuring-cron-schedules
So our final 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 mean our notification will be sent to those user who logged in 7 days ago. hope you got it.
Step 8: Run Scheduler Command For Test
now we are ready to run our cron, so you can manually check using following command of your cron. so let's run bellow command:
php artisan schedule:run
At last you can manage this command on scheduling task, 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
I hope it can help you.
#laravel-6 #laravel #cron-jobs #task-scheduling