Understanding Cron Jobs in Laravel
Oluwajubelo

Oluwajubelo @oluwajubelo1

About: I love writing codes

Location:
Lagos, Nigeria
Joined:
Mar 26, 2022

Understanding Cron Jobs in Laravel

Publish Date: Mar 11
5 10

Imagine you own a poultry farm 🐔, and every morning at exactly 6 AM, you need to feed your chickens automatically. You don’t want to wake up early every day to do it manually. So, you buy an automatic feeder that dispenses food at 6 AM on its own.

In Laravel, a cron job is like your automatic feeder. It allows you to schedule tasks that should run automatically at a specific time.

Why Do You Need a Cron Job?
Let's say you are running an e-commerce website 🛒, and you want to send a reminder email to customers every day at 9 AM about items left in their cart. Instead of sending these emails manually, you can create a Laravel cron job that handles it automatically.

How to Set Up a Cron Job in Laravel

Step 1: Create a Laravel Command

Laravel provides a way to define scheduled tasks using artisan commands. To create a new command, run:

php artisan make:command SendCartReminderEmails
Enter fullscreen mode Exit fullscreen mode

This will generate a file inside app/Console/Commands/ named SendCartReminderEmails.php.

Step 2: Define the Command’s Logic

Open the file app/Console/Commands/SendCartReminderEmails.php, and you will see a handle() method. This is where you define what should happen when the command runs.

Modify the handle() method like this:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use App\Mail\CartReminderMail;
use Illuminate\Support\Facades\Mail;

class SendCartReminderEmails extends Command
{
    protected $signature = 'email:cart-reminder'; // Command name
    protected $description = 'Send reminder emails to users about items in their cart';

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

    public function handle()
    {
        $users = User::whereHas('cart')->get(); // Get users with items in their cart

        foreach ($users as $user) {
            Mail::to($user->email)->send(new CartReminderMail($user));
        }

        $this->info('Cart reminder emails sent successfully!');
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Schedule the Command in Kernel

Now that we have our command, we need to tell Laravel when it should run.

Open app/Console/Kernel.php and inside the schedule() method, add:

protected function schedule(Schedule $schedule)
{
    $schedule->command('email:cart-reminder')->dailyAt('09:00'); // Runs every day at 9 AM
}
Enter fullscreen mode Exit fullscreen mode

Here are other ways you can schedule a job:

Schedule Expression

Step 4: Register Laravel's Scheduler in Crontab

Laravel’s scheduler does not run on its own. You need to register it in your server’s crontab (a list of scheduled tasks for Linux).

Run:

crontab -e
Enter fullscreen mode Exit fullscreen mode

Then add this line at the bottom:

* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
Enter fullscreen mode Exit fullscreen mode

🔹 Explanation:

* * * * * → Runs the Laravel scheduler every minute
php /path-to-your-project/artisan schedule:run → Runs Laravel's scheduled tasks
>> /dev/null 2>&1 → Hides output (optional)

Step 5: Test the Cron Job Manually

Before waiting for it to run automatically, you can test it by running:

php artisan schedule:run
Enter fullscreen mode Exit fullscreen mode

If everything is set up correctly, Laravel will execute the job immediately.

Final Thoughts

Just like how your automatic chicken feeder makes your life easier, cron jobs in Laravel help automate repetitive tasks like sending emails, clearing old records, or updating reports.

So now, instead of manually reminding users about their abandoned carts, your Laravel application will automatically do it for you every morning at 9 AM—just like clockwork! 🕘🔔

Would you like help setting up cron jobs for other use cases? 😊

Comments 10 total

  • Jane Smith
    Jane SmithMar 13, 2025

    That’s a great way to explain cron jobs! Laravel makes automating repetitive tasks like sending reminder emails a breeze with its scheduling feature. Setting up a Laravel cron job really does feel like having an automatic feeder for your app, just set it and forget it!

    • Oluwajubelo
      OluwajubeloMar 16, 2025

      you're absolutely right. "Laravel makes cron job a breeze with it's scheduling feature"

  • Daniel Ayo Akinleye
    Daniel Ayo AkinleyeMar 18, 2025

    Very detailed and helpful information.

    • Oluwajubelo
      OluwajubeloMar 18, 2025

      Thanks so much, glad you found this article helpful

  • Timilehin Abolaji Tim-Alex
    Timilehin Abolaji Tim-AlexMar 18, 2025

    This explanation is fantastic! The poultry farm analogy makes understanding cron jobs in Laravel so much easier. I love how you've broken down the setup into simple steps. Automating tasks can save so much time. Thanks for sharing!

    • Oluwajubelo
      OluwajubeloMar 18, 2025

      I'm glad you found this article helpful. Thanks alot

  • Chigozie Nwokoye
    Chigozie NwokoyeMar 18, 2025

    You did an impressive work explaining this, I am getting into working with cronjobs in laravel, and this has been very helpful in getting me started

    • Oluwajubelo
      OluwajubeloMar 18, 2025

      I'm glad you found this article helpful. Laravel makes working with corn job easy.

  • emmanuel oluwaloni
    emmanuel oluwaloniMar 18, 2025

    Wow, this is such a well-explained guide! 💡 The Laravel scheduler is a game-changer for automating tasks, and your example makes it super clear. I’ll definitely be using this for my projects. Do you have any tips on handling failed cron jobs or logging their execution? 🛠📜

    • Oluwajubelo
      OluwajubeloMar 18, 2025

      Thanks, i'm grateful you found this article helpful

      yea, below are some tips on handling failed cron jobs

      1. Log Cron Job Execution
      public function handle()
          {
              try {
                  // Your cron logic here
                  Log::info("MyCronJob executed successfully at " . now());
      
              } catch (\Exception $e) {
                  Log::error("MyCronJob failed: " . $e->getMessage());
              }
          }
      
      Enter fullscreen mode Exit fullscreen mode
      2. Redirect Cron Output to a Log File
      * * * * * php /path-to-your-project/artisan mycron:run >> /path-to-your-project/storage/logs/cron.log 2>&1
      
      Enter fullscreen mode Exit fullscreen mode
      3. Use Laravel Task Scheduling Logging
      protected function schedule(Schedule $schedule)
      {
          $schedule->command('mycron:run')
              ->everyMinute()
              ->appendOutputTo(storage_path('logs/cron.log'));
      }
      
      Enter fullscreen mode Exit fullscreen mode

      Use emailOutputTo('your@email.com') to get an email on failure.

      4. Detect & Restart Failed Jobs

      Use Laravel’s queue:failed to monitor job failures:

      php artisan queue:failed

      To retry failed jobs:
      php artisan queue:retry all

      5. Send Notifications on Failure

      Use Laravel notifications to alert admins when a job fails:

      use Illuminate\Support\Facades\Notification;
      use App\Notifications\CronJobFailed;
      
      try {
          // Your logic here
      } catch (\Exception $e) {
          Notification::route('mail', 'admin@example.com')->notify(new CronJobFailed($e->getMessage()));
      }
      
      Enter fullscreen mode Exit fullscreen mode
Add comment