Laravel / Laravel Artisan and CLI

Automating Tasks with Artisan Scheduling

In this tutorial, we will learn about task scheduling in Laravel. You'll learn how to define your command schedule within Laravel itself and automate tasks such as emailing and da…

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Explores Laravel's Artisan command-line interface for automation and productivity.

1. Introduction

In this tutorial, we will explore task scheduling in Laravel using Artisan. By leveraging the power of Laravel's built-in command scheduler, you will be able to automate various tasks such as sending emails and cleaning up the database.

What will you learn?
- How to define your command schedule within Laravel
- Automate tasks such as emailing and database cleanup

Prerequisites
- Basic understanding of Laravel and PHP
- Laravel environment setup on your machine

2. Step-by-Step Guide

In Laravel, the command scheduler is built on top of the Artisan command-line tool. It provides a fluent, expressive interface for defining command schedule within Laravel itself.

Create an Artisan Command

First, create a new command using the make:command Artisan command. For instance, if you want to create a command that clears the old data in the database:

php artisan make:command CleanDatabaseCommand

This command will create a new command class in the app/Console/Commands directory.

Define the Command's Behavior

Next, within the command class, you need to define the command's behavior in the handle method:

public function handle()
{
    DB::table('old_data')->delete();
}

The handle method is called when the command is executed. You can put your task logic in this method.

Schedule the Command

Finally, schedule your command in the schedule method of the App\Console\Kernel class:

protected function schedule(Schedule $schedule)
{
   $schedule->command('database:clean')->daily();
}

3. Code Examples

Let's put all these pieces together to create a task that sends a daily email:

// app/Console/Commands/EmailUsersCommand.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Mail\DailyReport;
use Illuminate\Support\Facades\Mail;

class EmailUsersCommand extends Command
{
    protected $signature = 'email:users';
    protected $description = 'Send a daily email to all users';

    public function handle()
    {
        $users = User::all();

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

        $this->info('Daily emails have been sent');
    }
}

Then, schedule this command in the Kernel class:

// app/Console/Kernel.php

protected function schedule(Schedule $schedule)
{
    $schedule->command('email:users')->daily();
}

This will send a daily email to all users.

4. Summary

In this tutorial, we’ve learned how to use Laravel's command scheduler to automate tasks. We've seen how to define a command's behavior and schedule it to run at specified intervals.

For further learning, you can explore other scheduling methods provided by Laravel, such as hourly, twiceDaily, and weekdays.

5. Practice Exercises

Exercise 1:

Create an Artisan command that clears the cache once a day.

Hint: Use the Cache::flush(); method to clear the cache.

Exercise 2:

Create an Artisan command that backups the database every week.

Hint: Use the Artisan::call('backup:run'); method to back up the database.

Exercise 3:

Create an Artisan command that sends an email to inactive users once a month.

Hint: You can define inactive users as users who haven’t logged in for the past month.

Remember, practice is key to mastering Laravel's task scheduling. Keep exploring and happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Backlink Checker

Analyze and validate backlinks.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help