How do i get the block machine name $block_id programmatically in Drupal 8?

$block_id = 'machine_name_to_determine';

$block_config = \Drupal\block\Entity\Block::load($block_id);
  • It really depends on where you're doing it and what information you have access to. Where are you putting this code? In a hook? If so what hook?
    – Amy
    Feb 28, 2019 at 18:52
  • You can query the block machine name with any information you have like plugin id, theme, region, ..., see drupal.stackexchange.com/questions/248324/…
    – 4uk4
    Feb 28, 2019 at 19:35

2 Answers 2


Here is a helper function to get the block content by machine name:

 * @param $machine_name
 * @return \Drupal\block_content\Entity\BlockContent|\Drupal\Core\Entity\EntityInterface|null
 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
 * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
function getBlockContentByMachineName($machine_name) {
  // Get the block id from machine name.
  $query_result = \Drupal::entityTypeManager()
    ->condition('machine_name', $machine_name)
    ->range(0, 1)
  // Get the block id.
  $block_id = reset($query_result);
  if ($block_id) {
    $block = \Drupal\block_content\Entity\BlockContent::load($block_id);
    return $block;
  else {
    return NULL;

Use example:

$machine_name = 'machine_name_to_determine';

$block_content = getBlockContentByMachineName($machine_name);

$block_content is an instance of BlockContent you can do what you want with it for example get the build using:

 $build = \Drupal::entityTypeManager()
$block_render = render($build);
  • 1
    This worked for me, except I had to replace machine_name with type in the query condition, using core 9.3.x Oct 12, 2022 at 2:37

Why do you need the block's machine name? You can get the block ID from the admin interface. Then you can load the block using the ID.

Go to the block layout page https://example.com/admin/structure/block and from there, you can get the block ID. Simply click or hover on edit to get the ID from the edit URL of a block.

$block_details = \Drupal::entityTypeManager()->getStorage('block_content')->load($block_id);
$body_value = $block_details->body->view('full');

In this way, you get the various values attached to a block. I don't know what you want exactly, I hope this code may help you.

Not the answer you're looking for? Browse other questions tagged or ask your own question.