Skip to main content

Update hooks

Update hooks automate database schema changes, data migrations, and environment-specific deployment tasks, so a change ships together with the code that needs it instead of being applied by hand.

Drupal provides several types of hooks for database updates. Understanding the differences helps you choose the right one for a deployment task.

Hook types overview

Hook typeUse caseExecutionFile location
hook_update_N()Database schema changes, data migrationsdrush updatedbMODULE.install
hook_post_update_NAME()Entity updates and other module operationsdrush updatedbMODULE.post_update.php
hook_deploy_NAME()Environment-specific deployment tasksdrush deploy:hookMODULE.deploy.php

All of these hooks run automatically during the provisioning process: drush updatedb runs the update and post-update hooks, and drush deploy:hook runs the deploy hooks.

To automate changes during site deployments, use deploy hooks. Note that deploy hooks run only once: Drupal tracks which hooks have been executed by name.

Example deploy hook

function ys_base_deploy_create_about_page(): string {
$environment = \Drupal\Core\Site\Settings::get('environment');

// Conditional execution based on environment.
if ($environment === ENVIRONMENT_PROD) {
return 'Skipped in production environment';
}

// Check if the About Us page already exists.
$node = \Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties(['type' => 'page']);
if (!empty($node)) {
return 'About Us page already exists';
}

$node = \Drupal\node\Entity\Node::create([
'type' => 'page',
'title' => 'About Us',
'body' => [
'value' => 'This is the About Us page content.',
'format' => 'basic_html',
],
]);

$node->save();

return 'Created About Us page';
}

Debugging commands

# Show pending deploy hooks.
drush deploy:hook-status

# Run deploy hooks manually (for testing).
drush deploy:hook