How can I flag content programmatically?
Here's how to flag or unflag an entity programmatically, using the Flag service.

$flag_id = 'bookmark';

$flag_service = \Drupal::service('flag');
$flag = $flag_service-&gt;getFlagById($flag_id);

// Flag an entity with a specific flag.
$flag_service-&gt;flag($flag, $entity);

// Unflag an entity with a specific flag.
$flag_service-&gt;unflag($flag, $entity);