Laravel 11 introduces a powerful feature: the shouldRun() method in migration classes. It allows you to conditionally execute a migration based on custom logic.
This is especially useful when:
- ✅ You want to avoid duplicate column additions.
 - ✅ Your migration depends on the presence of another table.
 - ✅ You want to ensure foreign keys or indexes don’t already exist.
 
๐ ️ Step 1: Install Laravel 11
composer create-project "laravel/laravel:^11.0" conditional-migration
  ๐️ Step 2: Configure Database
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password
  ๐ฆ Step 3: Run Default Migrations
php artisan migrate
  ✏️ Step 4: Create a New Migration
php artisan make:migration add_profile_completed_to_users_table
  Edit the migration file to use shouldRun():
public function shouldRun(): bool
{
    return !Schema::hasColumn('users', 'profile_completed');
}
public function up(): void
{
    Schema::table('users', function (Blueprint $table) {
        $table->boolean('profile_completed')->default(false);
    });
}
  ๐ Step 5: Run the Migration
php artisan migrate
  ๐ Step 6: Test Conditional Behavior
php artisan migrate
  The migration is skipped if already applied.
๐งช Bonus: Manual Test
- Remove the entry from the 
migrationstable. - Run 
php artisan migrateagain. 
✅ Conclusion
The shouldRun() method in Laravel 11 helps create smarter, idempotent migrations with safe checks. It’s a great addition for complex applications with evolving schemas.
    ๐ GitHub Repository: 
    
      Laravel 11 Conditional Migration Demo
    
  
Comments
Post a Comment