How to set up Task Scheduling with Cron job in Laravel ?

Laravel’s command scheduler offers an approach to managing scheduled tasks on your server. The scheduler allows you to fluently and expressively define your command schedule within your Laravel application itself. 

We will run the Cron job in our local server and Live Server in this blog, the code and workflow are the same but when we schedule the Cron job in the live server, we make some changes let’s see.

Generating Migrations

At first, we create a new migration file for test_cron_table.

php artisan make:migration create_testcron_table

Migration Structure

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTestcronTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('testcron', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('testcron');
    }
}


Running Migrations

After defining columns and his data types For migrating in cmd terminal hit the given below command

php artisan migrate

Insert some Data Manually

Cron job in Laravel

Create Model

After making the table, we will make a new model.

php artisan make:model TestCron

app/TestCron

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class TestCron extends Model
{
    protected $table = 'test_cron';
}

After making the TestCron model, we make a new command DemoCron, where we will perform our task with the help of some logic.

php artisan make:command DemoCron

app/Commands/DemoCron.php

In the DemoCron.php file, we write our logic and also we define The name and signature of the console command and The console command description.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\TestCron;
use Carbon\Carbon;

class DemoCron extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'delete:data';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Delete Data Test cron Table 30 days old';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        TestCron::whereDate('created_at', '<', Carbon::now()->subDays(30))
        ->update([
            'deleted_at' => Carbon::now()
        ]);

        $this->info('Demo:Cron Cummand Run successfully!');
    }
}

php artisan:list

You can see the DemoCron command with signature and description in Terminal with the help of php artisan:list command.

Cron job in Laravel

Defining Schedules

app/Commands/Kernal.php

You may define all of your scheduled tasks in the schedule method of your application’s App\Console\Kernel class. To get started, let’s take a look.

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\DemoCron::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('delete:data')
                 ->everyMinute();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

We register our command in Kernal.php like :

$schedule->command(‘delete:data’)
->everyMinute();

You can use minute, hourly, daily, weekly, monthly, yearly, and more. for Scheduling Job.

<strong>Complete Documentation</strong> : <a href="https://laravel.com/docs/7.x/scheduling" target="_blank" rel="noreferrer noopener">https://laravel.com/docs/7.x/scheduling</a>

Starting The Scheduler

Now, we will run our Scheduler in our local server with the help of these given commands, and you can run both commands, Both commands work the same, but the main difference is when you have multiple Cron Jobs you can run php artisan schedule:run

but when we want to run a single Job then we run php artisan delete:data command.

php artisan schedule:run
php artisan delete:data
Cron job in Laravel

In DemoCron.php file we wrote a logic in the public function handle, that’s why the older value deleted from the table after the run the Schedule command.

public function handle()
    {
        TestCron::whereDate('created_at', '<', Carbon::now()->subDays(30))
        ->update([
            'deleted_at' => Carbon::now()
        ]);

        $this->info('Demo:Cron Cummand Run successfully!');
    }

Output Local Server :

Cron job in Laravel

Starting The Scheduler in Live Server

Cron job in Laravel
Cron job in Laravel
Cron job in Laravel
Cron job in Laravel
Cron job in Laravel

Hi, My name is Gaurav Pandey. I'm a Laravel developer, owner of 8Bityard. I live in Uttarakhand - India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Javascript, JQuery, Laravel, WordPress. connect@8bityard.com

Scroll to Top