How to programmatically add a language

Components

Sometimes you have to add a new language in Drupal 8/9 programmatically. For example, maybe you need to write an update hook that will add a new language. This is how you can do it:

use Drupal\language\Entity\ConfigurableLanguage;

$language = ConfigurableLanguage::createFromLangcode('sr');
$language->save();

If you don't know the langcode, you can find it by inspecting the select box on the /admin/config/regional/language/add page. 

About the Author

Goran Nikolovski is an experienced web and AI developer skilled in Drupal, React, and React Native. He founded this website and enjoys sharing his knowledge.