Automate: Scheduling Artisan Commands in Laravel

Laravel Task Scheduling lets you automate recurring tasks without needing a separate cron job for each one. This is especially useful for tasks like sending daily emails or clearing out old data.


Step 1: Create an Artisan Command

Generate a custom Artisan command if you don’t already have one. Here’s an example that clears old logs.

php artisan make:command ClearOldLogs

In the command file (ClearOldLogs.php), define the functionality:

use Illuminate\Console\Command;

class ClearOldLogs extends Command
{
    protected $signature = 'logs:clear';
    protected $description = 'Clear old log files';

    public function handle()
    {
        // Clear logs older than 30 days
        \File::delete(storage_path('logs/*.log'));
        $this->info('Old logs cleared successfully!');
    }
}

Step 2: Schedule the Command

Open App\Console\Kernel.php and add the command to the schedule method.

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

This will run the logs:clear command every day at midnight.

Step 3: Set Up Cron to Run Laravel Scheduler

To make this work, add a single cron entry to run Laravel’s scheduler every minute:

* * * * * php /var/www/my-laravel-app/artisan schedule:run >> /dev/null 2>&1

The cron job runs every minute to determine if any tasks are due, regardless of their specific frequency (daily, hourly, etc.).

With Laravel Task Scheduling, you can easily automate Artisan commands and other recurring tasks, making maintenance much simpler.