How to delete block on hook_uninstall? I have a custom module, mymodule, that will create custom blocks, block_test and block_test2 on mymodule_install().

When the module is uninstalled, I want to remove any blocks created by mymodule. How would I delete the block generated by a module being uninstalled?

drush command (local dev):

drush pmu mymodule -yv


mymodule.uninstall()

function mymodule_uninstall() {
  // Delete Blocks generated by module.

  /** @var \Drupal\Core\Entity\EntityStorageInterface $block_storage */
  $block_storage = \Drupal::service('entity_type.manager')-&gt;getStorage('block');
  /** @var \Drupal\block\Entity\Block[] $blocks */
  $blocks = $block_storage-&gt;loadMultiple();
  foreach ($blocks as $block) {
    // I am stuck here. 
  }
}
Yes, then the best thing would be to follow the enforced config dependencies part above, if you create the content blocks with a fixed uuid then you can just put the block config entities in your config/install folder, with the config dependencies as explained there and it should be uninstalled automatically.

At least the config entities, if you want to delete the block_content entities too then load them by UUID with $block_content = \Drupal::service('entity.repository')-&gt;loadEntityByUuid('block_content', 'YOUR_UUID'); $block_content-&gt;delete()