21 C
Jaipur
Friday, November 27, 2020

Laravel Scheduler Tutorial – Linux Hint

Must read

How To Earn Money Via Google Task Mate In India [Get Referral Code]

Google has recently launched a new app called Task Mate that lets users earn money by completing simple tasks such as taking pictures or...

How To Perform Quick “Chrome Actions” From Chrome’s Address Bar?

If you use Google Chrome regularly, you know that a lot can be done or fixed in the Google Chrome settings. However, more often...

Indian Government Caps Fee and Surge Pricing of Ride-Hailing Apps like Uber and Ola

The Ministry of Road Transport and Highways has issued new guidelines for ride-hailing companies such as Uber and Ola that allow aggregators to charge...

How to Install and Setup Let’s Encrypt (Certbot) on Linux

Getting an HTTPS certificate for your website is not anymore an optional choice. If you are a website developer, you might know that Google...

Some tasks are required to perform on regular basis in any application, and it would be more efficient if the tasks could be done automatically. The Laravel framework makes these types of tasks easier by using Laravel Scheduler. Sending offer-related bulk emails, optimizing data, generating reports, keeping application backup, and removing inactive users are some common examples of the repetitive tasks that can be performed with the Laravel Scheduler. Laravel can execute specific tasks periodically by using a built-in task manager named Corn job. The configuration file named Corntab is used by Corn to manage scheduling tasks. This tutorial shows you how to manage repetitive tasks by creating Corn jobs and performing task scheduling.

Prerequisites

Before beginning this tutorial, first, complete the following tasks:

  1. Create a new Laravel project
  2. Set up the database connection
  3. Run the migrate command create a user table
  4. Set up the configuration for sending emails (SMTP is used here for sending emails.)

Implement Default Authentication

First, implement the default user authentication system of Laravel to complete the scheduling task shown in this tutorial. Run the following commands from the terminal to implement the default Laravel authentication using Vue.

$ composer require laravel/ui
$ php artisan ui vue –auth

Run the following command to compile the fresh scaffolding to get the updated content.

$ npm install && npm run dev

Run the following command to clear the route cache.

$ php artisan route:clear

Run the following command to start the Laravel development server and check whether the default user authentication system is working.

Open any browser and run the following URL in the browser. If the login and register link appears and works properly, then the implementation of the default authentication has been completed properly.

Create a Mailable Class and Artisan Command

Many new users will create accounts daily and will perform many tasks related to registered users when the project is online. Sometimes, the application needs to know how many users have created accounts each day. If this information is required on a regular basis, then it is better to execute a particular query after a regular interval. A Laravel command is used here to get the information of the currently registered users and a mailable class is used to send that information via email to the admin or a specified person.

Run the following command to create the mailable class for sending the email. It will create a file named SendUsersList.php in the location app/Mail.

$ php artisan make:mail SendUsersList

Open the file and modify the content, as in the following code.

<?php

namespace AppMail;

use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateMailMailable;
use IlluminateQueueSerializesModels;

class SendUsersList extends Mailable
{
use Queueable, SerializesModels;

/* Declare an array variable */
public $userList= array();

/**
* Create a new message instance.
*
* @return void
*/

public function __construct($userList)
{
/* Initialize the array variable by the variable passed by the
object creation of the class. */

$this->userList = $userList;
}

/**
* Build the message.
*
* @return $this
*/

public function build()
{
/* Diaplay the view file with the values of the array variable */
return $this->view(‘registeredList’)->with(‘userList’,$this->userList);
}
}

Run the following command to create the custom Laravel command named RegisterUsersList, which will execute the query to get the list of registered users information in each day. The command will create a file named RegisterUsersList.php in the location app/Commands.

$ php artisan make:command RegisterUsersList command=registered:users

Open the file and modify the content with the following code to send the list of currently registered users of the current system to a particular email address.

<?php

namespace AppConsoleCommands;

use IlluminateConsoleCommand;

/* Import necessary packages */
use Mail;
use AppMailSendUsersList;
use DB;
use CarbonCarbon;
use AppConsoleCommandsDateTime;

class RegisterUsersList extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/

/* Add signature value */
protected $signature = ‘registered:users’;

/**
* The console command description.
*
* @var string
*/

protected $description = ‘List of registered users’;

/**
* Create a new command instance.
*
* @return void
*/

public function __construct()
{
parent::__construct();
}

/**
* Execute the console command.
*
* @return int
*/

public function handle()
{
/* Read the current system date */
$today =Carbon::now()->toDateString();

/* Get the list of users information who are registered
in the current system date */

$current_registered_users = DB::table(‘users’)->whereDate(‘created_at’, $today)->get()->toArray();
/* Create the object of the mailable class with the array variable
that contains the currently registered users list */

$email = new SendUsersList($current_registered_users);

/* Send email using Mail class */
Mail::to(‘receiver email address’)->send($email);
}
}

Set Up the Schedule to Execute the Command

Open the Kernel.php file from the location app/Console and modify the content with the following code. You can set different types of schedule frequency options. You can get the list from this link. Here, the hourly schedule is used.

<?php

namespace AppConsole;

use IlluminateConsoleSchedulingSchedule;
use IlluminateFoundationConsoleKernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/

/* Intialize the $commands variable */
protected $commands = [
‘AppConsoleCommandsRegisterUsersList’,
];

/**
* Define the application’s command schedule.
*
* @param IlluminateConsoleSchedulingSchedule $schedule
* @return void
*/

protected function schedule(Schedule $schedule)
{
/* Set the schedule hourly */
$schedule->command(‘registered:users’)->hourly();
}

/**
* Register the commands for the application.
*
* @return void
*/

protected function commands()
{
$this->load(__DIR__.‘/Commands’);

require base_path(‘routes/console.php’);
}
}

Create View

Create the registeredList.blade.php view file with the following code.

<div>
@if (count($userList) > 0)
<p>The list of users registered today are given below:</p>
@foreach($userList as $user)
{{$user->name}} <br/>
@endforeach
@else
No user is registered today yet.
@endif
</div>

Run the command:

Run the following commands to clear the cache.

$ php artisan cache:clear
$ php artisan config:cache

Run the following artisan command from the terminal to execute the previously created custom command and check the output.

$ php artisan registered:users

Check the receiver email address to find out the output. The following output will appear if no user is created.

Create a new user account and check the email again.

Conclusion

The Laravel Scheduler makes repetitive tasks easier to perform for the application. After reading this tutorial, readers should now have a clear understanding of the concepts of creating custom commands and implementing automated tasks using Laravel Scheduler.

Source link

- Advertisement -

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article

How To Earn Money Via Google Task Mate In India [Get Referral Code]

Google has recently launched a new app called Task Mate that lets users earn money by completing simple tasks such as taking pictures or...

How To Perform Quick “Chrome Actions” From Chrome’s Address Bar?

If you use Google Chrome regularly, you know that a lot can be done or fixed in the Google Chrome settings. However, more often...

Indian Government Caps Fee and Surge Pricing of Ride-Hailing Apps like Uber and Ola

The Ministry of Road Transport and Highways has issued new guidelines for ride-hailing companies such as Uber and Ola that allow aggregators to charge...

How to Install and Setup Let’s Encrypt (Certbot) on Linux

Getting an HTTPS certificate for your website is not anymore an optional choice. If you are a website developer, you might know that Google...

India Wearables Shipments Hit Record High in Q3 Amidst Falling Prices, Increased Options

Shipments of smart wearables in India reportedly jumped 165% in the July-September quarter thanks to an increased emphasis on remote work and rising health...