Search code examples
phplaravelcronmigrationcommand

Automated Laravel Migration unable to complete


I've a SAAS application where tenant separation is per database. When a new customer signs up,account is provisioned by series of automated custom Laravel commands (Using Task Scheduler/Cron Job). One of them is tenant database migration. On the process of updating the app I added new migrations to create an additional table and add and drop some columns from other tables. When the migration for new tenant is executed, only the old migrations are run. Migration will complete only when I run the command manually(Without cron job) on localhost or production. No errors to hint as to why the migration is not being completed. Am I missing something? Below is the code snippet for the command.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Account;
use App\Traits\SwitchToAccountsManager;
use App\Traits\SwitchToTenantDatabase;
use DB;

class MigrateNewTenant extends Command
{
    use SwitchToAccountsManager,SwitchToTenantDatabase;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'migrate:new';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Runs migration on all new tenants databases';

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

        $this->SwitchToAccounts();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $tenants=Account::where('db_created','Yes')->where('tables_created','No')->get();

        $bar = $this->output->createProgressBar(count($tenants));

        foreach ($tenants as $tenant) {
            if(!empty($tenant->db_name)){
                
                $account_id=$tenant->account_id;

                //Set tenant database connection
                $this->SwitchToTenantDB($tenant->db_name);
            
                //Run migration
                $this->info("Running migration for: ".$tenant->db_name);
                $this->call('migrate',["--force" => true]);

                //Switch back to tenants manager
               $this->SwitchToAccounts();

                //Mark tables as created/migrated
                DB::table('accounts')
                    ->where('account_id', $account_id)
                    ->update(['tables_created' => 'Yes']);
            }else{
                $this->info("Skipping migration for: ".$tenant->name);
            }
            $bar->advance();
        }
    
        $bar->finish();
    }
}

Due to incomplete migration customers are encountering errors. I've to re-run migrations manually.


Solution

  • I discovered the cron job was executing php artisan chedule:run command on staging application not production.