Setup Laravel Cronjobs for subdomains or multi tenant

Tamrakar Shreyaa
3 min readMar 28, 2024

Laravel’s Task Scheduler enables you to define and manage time-based tasks, known as cron jobs, on Unix-based systems. It provides an expressive syntax and commands for automating these tasks at specified intervals.

Install Laravel Project

Run the command to induct fresh Laravel project.

composer create-project laravel/laravel cronjob

Define your scheduled task by specifying the command

Open the app/Console/Kernel.php file.

<?php

namespace App\Console;

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

class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{

$schedule->command('demo:cronjob')->everyMinute();
}

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

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

Create the Cronjob

php artisan make:command DemoCronJob

Implement the Cronjob Logic

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use App\Models\Adminpanel\General\SubDomain;
use Config;




class DemoCronJob extends Command
{
protected $signature = 'demo:conjob';
protected $description = 'demo cronjob example';




public function handle()
{
// Get all subdomains
$subdomains = SubDomain::all();

foreach ($subdomains as $subdomain) {
// Process data for each subdomain


$dbConfig = config('database.connections.mysql');

//now use database name which is in user record;
$dbConfig['database'] = $subdomain->name;
// dd($dbConfig);

$dbConfig['username'] = $subdomain->user;
$dbConfig['password'] = $subdomain->password;

$connection_name = "auto_check_in_cron_".$subdomain->name;

Config::set("database.connections.".$connection_name, $dbConfig);
Config::set("database.default",$connection_name);
DB::purge($connection_name);
DB::reconnect($connection_name);

//set mail
$filePath = config_path('mail-' . $subdomain->name . '.php');

if (file_exists($filePath)) {
Log::error("in subdomain mail".''.$filePath);
$originalMailConfig = config('mail'); // Store original mail config
Config::set('mail', include $filePath);

Log::info('Mail from address: ' . config('mail.from.address'));
Log::info('Mail from name: ' . config('mail.from.name'));
}

Log::info($dbConfig['database'] . ' ' .$subdomain->email);

$this->processSubdomainData($subdomain);
Log::info("------------------------");
// Reset mail configuration
if (isset($originalMailConfig)) {
Config::set('mail', $originalMailConfig);
unset($originalMailConfig); // Clean up
}

Config::set("database.default", 'mysql');
\Illuminate\Support\Facades\Artisan::call('config:cache');
\Illuminate\Support\Facades\Artisan::call('config:clear');
\Illuminate\Support\Facades\Artisan::call('cache:clear');


}
}


private function processSubdomainData($subdomain)
{

// Implement logic to process data for the given subdomain
// This could be sending emails, generating reports, etc.
$this->info('demo cronjob executed successfully!');
}
}

Configure the subdomain mail

create the config/mail-subdomain_name.php file.

<?php
return [
'driver' => 'smtp',
'host' => 'smtp.gmail.com',
'port' => 587,
'username' => 'subdomain mail id',
'password' => 'app password',
'encryption' => 'tls',
'from' => [
'address' => 'subdomain mail id',
'name' => 'app name /subdomain app name',
],
];

Configure the Cronjob

crontab -e

Add the following line to the file to run laravel scheduler every minute:

* * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1
OR
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

Tracking cronjob output

Laravel automatically records the output of scheduled tasks in the storage/logs/schedule.log or storage/logs/laravel.log file. You can periodically review this file to verify that your tasks are executing correctly.

--

--

Tamrakar Shreyaa

Laravel | PHP | API | AJAX | jQuery | Laravel vue | Livewire | LAMP stack | CI CD