Paragraphs give great power to drupal 8. This code will show you how you can add them programmatically, for example when importing stuff. In this tutorial, we'll: 

  • 1) Create two paragraphs: one with text and one with a referenced media item
  • 2) Save them to your node

1. Programmatic creation of paragraphs

Before adding anything to nodes, we have to create the paragraphs first.

$body = '<p>My html text</p>'
$textparagraph = Paragraph::create([
  'type' => 'text',
  'field_text' => array(
    "value"  =>  $body,
    "format" => "basic_html"
  ),
]);
$textparagraph->save();

Second, the media entity paragraph. This takes a bit longer.

$directory = public://media;
$url = 'https://mysite.com/mymediafile.jpg';
if(file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) {
  $file = system_retrieve_file(trim($url), $directory, true);
}
$drupalMedia = Media::create([
  'bundle' => 'image',
  'uid' => '0',
  'field_media_image' => [
    'target_id' => $file->id(),
  ],
]);
$drupalMedia->setPublished(TRUE)
  ->save();

$imageparagraph = Paragraph::create([
  'type' => 'image',
  'field_media' => array(
    'target_id'  =>  $drupalMedia->id(),
  )
]);
$imageparagraph->save();

2. Create the node and attach the paragraphs

$node = Node::create([
    'type'        => 'article',
    'title'       => 'My title',
    'field_paragraphs'  => array(
      array(
        'target_id' => $imageparagraph->id(),
        'target_revision_id' => $imageparagraph->getRevisionId(),
      ),
      array(
        'target_id' => $textparagraph->id(),
        'target_revision_id' => $textparagraph->getRevisionId(),
      ),
    ),
    'created' => time(),
]);
$node->save();

We're done. We have now created a node with two paragraphs. Enjoy!