Using Cron Schedule in Laravel to Automate Tasks

Cron job is useful to automate our task at the specified time in regular intervals. Laravel ships with a feature for task scheduling which makes cron schedule super easy. In past, we need to add a separate entry for each cron job. In the Laravel, we just need to add one command and it runs all our cron jobs automatically. There is no need of adding a separate entry for each task. In this article, we study of using cron schedule in Laravel which help us to automate our tasks.

Why We Need to Run Cron?

There are several examples we can mention where we need to run a cron. You may be running an online store and you want to send promotional offers to your users. Or you have a membership website and you need to send the reminder email to users about their renewal subscription period. These are the two examples where we can use the cron. What we do is, write a program which can perform this task and set a cron for it. Your server will look for the time specified for cron and when that time hits it automatically run the program. We don’t need to look at the clock and run the program manually.

This process makes our life easy. We can focus on our other important stuff and invest time in a wise thing.

Cron Schedule in Laravel

For our article, let’s take a real-world example. Let’s say we have a bunch of users in our Laravel database. Each midnight we need to send an email to all users describing our new promotional offer. Doing so, our users get notified about new offers and your sales can get more attention.

We are assuming you stored all your user’s information in the ‘users’ table. We will get user’s emails from this table and send them an email. Of course, we need to write a code in a way which should run every midnight.

Open the app/Console/Kernel.php file in your editor and add the user model and Mail facade to the file.

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\User; // User model
use Mail; // Mail Facade

class Kernel extends ConsoleKernel
{
    ....

Kernal class has a method schedule where we have to write one or multiple schedules. As we need to send an email to our users we write the code as follows.

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\User;
use Mail;

class Kernel extends ConsoleKernel
{
    ....

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->call(function () {
            $arr_users = User::all();

            if(count($arr_users) > 0) {
                foreach ($arr_users as $user) {
                    $name = $user->name;
                    $email = $user->email;
                    $data = array("name" => $name, "body" => "This is our new promotional offer");
                    Mail::send('emails.mail', $data, function($message) use ($name, $email) {
                        $message->to($email, $name)
                                ->subject('New Offer Launched');
                        $message->from('admin@artisansweb.net', 'Artisans Web');
                    });
                }
            }
        })->daily();

        // tou can add more schedules here
    }
    ....

In the code above, we take users from the database and send them an email using send method of the Mail facade. Here we need to create a mail.blade.php files under the resources/views/emails directory.

mail.blade.php

Hi <strong>{{ $name }}</strong>,

<p>{{ $body }}</p>

As our task is send an email at the midnight we used the daily() method. Laravel provides different schedule frequency options which you would get on the documentation page.

Add Cron Entry to Your Server

Finally, to set this cron job on a server you should add below cron entry to your server.

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

Make sure you have set the path of your project correctly. This Cron will call the Laravel command scheduler every minute. It automatically executes schedule:run command and evaluate your scheduled tasks and runs the tasks that are due.

We hope you may have learned about using cron schedule in Laravel and automate your tasks. We would like to hear your thoughts in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *