Laravel Conditional Migrations: shouldRun()

Laravel's shouldRun() method in migrations for feature flags, conditional execution, environment-based migrations, and staged deployments.

February 6, 20262 min readssbhattarai

What is shouldRun()?

Control when migrations execute by adding a shouldRun() method. If it returns false, the migration is skipped during php artisan migrate.

Basic Use Case

public function shouldRun(): bool
{
    return app()->environment('production');
}

Run specific migrations only in production.

In a real-time scenario involving a multitenant architecture, the situation would unfold as follows:

public function shouldRun(): bool
{
    return config('app.tenant_mode') === 'enterprise';
}

Run migrations only for specific tenant tiers.

Complete Sample Migrations

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Laravel\Pennant\Feature;

return new class extends Migration
{
    /**
     * Determine if this migration should run.
     */
    public function shouldRun(): bool
    {
        return Feature::active('enable-subscriptions');
    }
    
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('subscriptions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained();
            $table->string('plan');
            $table->timestamp('expires_at');
            $table->timestamps();
        });
    }
    
    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('subscriptions');
    }
};

If you would like to see which migrations have already run and which are still pending, you may use the migrate:status Artisan command:

php artisan migrate:status

Pro Tip: Use shouldRun() for optional features, but never for critical schema changes. Critical migrations should always run to keep databases in sync.