Add translation to a term or node programmatically in Drupal 8

Add translation to a term or node programmatically in Drupal 8

It's really easy to create a node or a term programmatically in Drupal 8. Here is the script to create term programmatically.

$term = Term::create([ 
    'name' => 'Apple',
    'vid' => 1, 
  ]);
$term->save();

But a small change in this simple script will allow you to added translation for this term as well.

$term = Term::create([ 
    'name' => 'Apple',
    'vid' => 1,
  ]);
// Add translation.
$term->addTranslation('ar', ['name' => 'Apfel',]);
$term->save();

Similarly, translations can be added to a node or any other entity programmatically.