0
0
Laravelframework~30 mins

Scheduler with cron in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Scheduler with cron in Laravel
📖 Scenario: You are building a Laravel application that needs to run a task every minute to clean up old records. You will set up a scheduler using Laravel's task scheduling system and configure a cron job to trigger it.
🎯 Goal: Create a Laravel command, schedule it to run every minute using Laravel's scheduler, and configure the cron entry to run the scheduler.
📋 What You'll Learn
Create a Laravel command named CleanupOldRecords
Schedule the command to run every minute in app/Console/Kernel.php
Add the cron entry to run Laravel's scheduler every minute
💡 Why This Matters
🌍 Real World
Many web applications need to perform regular maintenance tasks like cleaning old data or sending notifications. Laravel's scheduler with cron makes this easy and reliable.
💼 Career
Understanding Laravel's task scheduling and cron integration is essential for backend developers working with Laravel to automate repetitive tasks efficiently.
Progress0 / 4 steps
1
Create the Laravel command CleanupOldRecords
Run the artisan command to create a new command named CleanupOldRecords inside the app/Console/Commands directory.
Laravel
Need a hint?

Use php artisan make:command CleanupOldRecords to create the command.

2
Schedule the CleanupOldRecords command every minute
Open app/Console/Kernel.php and add the line $schedule->command('cleanup:oldrecords')->everyMinute(); inside the schedule method.
Laravel
Need a hint?

Inside the schedule method, use $schedule->command('cleanup:oldrecords')->everyMinute();.

3
Add the cron entry to run Laravel scheduler every minute
Add the following cron entry to your server's crontab: * * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1. Replace /path-to-your-project with your Laravel project path.
Laravel
Need a hint?

Use crontab -e to edit the cron jobs and add the line to run Laravel's scheduler every minute.

4
Complete the CleanupOldRecords command handle method
Open app/Console/Commands/CleanupOldRecords.php and add a handle method that deletes records older than 30 days from the old_records table using Eloquent's whereDate and delete methods.
Laravel
Need a hint?

Use Carbon to get the date 30 days ago and delete records older than that from the old_records table.