How to Create A Cron Job in Laravel 5.7, 5.8 (Cronjob to notify users for resubscription before expiration date)….

Web application sometimes may require some tasks to run periodically on the server without supervision.. How do we achieve this ? To achieve this, a task scheduling system is required such could be for sending promotional emails, optimizing database, creating backups or generating site traffic report.

In this blog post, we would be creating a task scheduling system to notify our subscribers on our platform to repay for subscription before their expiration date.

Cron

Cron is a time-based task scheduler in Unix/Linux operating systems. It runs shell commands at a pre-specified time period. Cron uses a configuration file called crontab also known as Cron table to manage the task scheduling process.

Crontab contains all the Cron jobs related to a specific task. Cron jobs are composed of two parts, the Cron expression, and a shell command that needs to be run.

* * * * * command/to/run1

In the Cron expression above (* * * * *), each field is an option for determining the task schedule frequency. These options represent minute, hour, day of the month, month and day of the week in the given order. Asterisk symbol means all possible values. So, the above command will run every minute.

The Cron job below will be executed at 6:20 on 10th of every month.

20 6 10 * * command/to/run

Laravel Cron Job

Laravel Cron Job is an inbuilt task manager that gives your applications the ability to execute specific commands like sending a slack notification or removing inactive users at a periodic time. We will be using the latest version of Laravel, which is 5.6 at the time of writing this article.

You need a Linux Operating System to run Cron Jobs. This tutorial also assumes a fair knowledge of PHP and Laravel.

Creating a new Project

In this tutorial, we will create a simple laravel application to demonstrate task scheduling. Before we continue, i assume you have basic knowledge of php and laravel as i will be quick.

composer create-project --prefer-dist laravel/laravel cron

Lets make our authentication

php artisan make:auth

Lets create our Tables:

Users Table by default

SubscriptionTable..

SubscriptionPayments

Lets make our authentication

Our models for our Relationship ..

UserModel.php
SubscriptionModel.php
php artisan make:command SubscriptionRepayment

results to this….

<?phpnamespace App\Console\Commands;
use Illuminate\Console\Command;
class SubscriptionRepayment extends Command{/*** The name and signature of the console command.** @var string*/protected $signature = 'command:name';/*** The console command description.** @var string*/protected $description = 'Command description';/*** Create a new command instance.** @return void*/public function __construct(){parent::__construct();}/*** Execute the console command.** @return mixed*/public function handle(){//}}

In this code, protected $signature = 'command:name' contains the name and signature of command we will create

so lets make ours ….

Replace the words command:name with subscription:repayment. This is what we will call this when running the command to perform the task.

Next to protected $description ='Command description'. This is where you place the actual description of what this command will do. The description will be shown when you run the php artisan list.

Change the description of the command to:

protected $description = 'Notify users for resubscription';

MORE………………

Lets break it down….

//get all payment details
$userPayments= SubscriptionPayment::with('subscription')->get();
foreach($userPayments as $payment){//loop through our payment details and perform my action//
}

//finally logs this to the console if successfully
$this->info('Repayment Notification has been Sent');

Now time for the Maths..I want to send a notification to a user 3 days before his expiration, what do i do ? Subtract 3 days from the expiration, then check if the current day is equal to the value of 3 days before expiration then i send him a notification mail.

$expirationDate = $payment->expiration_date;//Subtracts 3days from the expiration date
$carbon3DaysBeforeExpirationDate = Carbon::parse($expirationDate)->subDay(3)->toDateString();

Same with this…..

//Subtracts 2days from the expiration date$carbon2DaysBeforeExpirationDate = Carbon::parse($expirationDate)->subDay(2)->toDateString();//Subtracts a day from the expiration date$carbon1DayBeforeExpirationDate = Carbon::parse($expirationDate)->subDay(1)->toDateString();//  if currentDate is 3days or 2 days or a day before the expiration perform the below actionif($currentDate == $carbon3DaysBeforeExpirationDate || $carbon2DaysBeforeExpirationDate || $carbon1DayBeforeExpirationDate){Mail::to($payment->user->email)->send(new NewPay($data));}//the logs this to the console$this->info('Repayment Notification has been Sent');

So we are done creating our command , so lets create our mail

php artisan make:mail ResubscriptionMail

Now that you have created the command, you will need to register it in the Kernel.

Go to app/Console/Kernel.php

In this file, we register the command class in the commands property and we schedule commands to be executed at periodic intervals in the schedule method. This is where we handle all the Cron Jobs in Laravel.

Change this file with the contents below. We have simply added our SubscriptionRepayment class to the commands property and schedule it to run every day.

Now, if you run the php artisan list command in the terminal, you will see your command has been registered. You will be able to see the command name with the signature and description.

Let’s highlight some things:

i) Commands\SubscriptionRepayment::class, refers to subscriptionRepayment class where we handled the command

ii) $schedule->command('subscription:repayment') is where we define which command needs to be executed and ->daily();

You can replace ->daily(); with another time interval option from the following list. You can find more about Task Scheduling in Laravel Documentation.

Don’t forget to setup mail credentials in the .env file and make sure you have details in the users table and other tables in the database. Execute the command itself on the terminal:

 php artisan subscription:repayment

Starting the Laravel Scheduler

Let’s setup the Cron Jobs to run automatically without initiating manually by running the command. To start the Laravel Scheduler , we only need to add one Cron job which executes every minute. Go to your terminal, ssh into your server, cd into your project and run this command.

crontab -e

This will open the server Crontab file, paste the code below into the file, save and then exit.

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

Do not forget to replace /path/to/artisan with the full path to the Artisan command of your Laravel Application.

One of the most important advantages of Laravel Task Scheduler is that we can focus on creating commands, writing logic and Laravel takes care of the rest.

Next thing we should is to mmm ……………………….

Nothing actually gotcha ..

Thank you for reading…

Credits to https://tutsforweb.com.. for this swift blog post..

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store