Is there a way to figure out the block machine name? In Drupal 8, is there a way to figure out what current block or view machine name you should use?

For example, with the following code, I noticed that 'machine_name_to_determine' could change depending on how many times you have used your block.

$block_id = 'machine_name_to_determine';
$block_config = \Drupal\block\Entity\Block::load($block_id);


I need a way to retrieve this at run-time. How can I retrieve it?
You can query the blocks by the plugin id. This is the id of a block plugin or for derivatives like a view block (which you probably are looking for as you've mentioned a view machine name) with additional parameters:

$plugin_id = 'views_block:' . $view_id . '-' . $display_id;


Where $view_id is the view machine name which you find in the Views UI and $display_id is the display machine name, usually block_1 for the first block of the view.

Then get all blocks placed for this plugin id and print the block machine names or use the loaded blocks in your code:

$blocks = \Drupal::entityTypeManager()-&gt;getStorage('block')
  -&gt;loadByProperties(['plugin' =&gt; $plugin_id]);
foreach ($blocks as $block) {
  echo $block-&gt;id();
}


Add a theme or region to loadByProperties() if needed:

['theme' =&gt; 'bartik', 'region' =&gt; 'header']