Programmatically Create Node With Image Field - Drupal 8

Submitted by leopathu on Sun, 05/08/2022 - 02:39

Drupal have proper UI to create nodes but programmer should know to create a node programmatically, It might need in a custom module or any scripts. The following code would help to create node with the image field in drupal 8,

use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;
//Save Image in local from remote data.
$data = file_get_contents("path/data-folder/sample.png");
$file = file_save_data($data, "public://sample.png", FILE_EXISTS_REPLACE);
// Create node object and save it.
$node = Node::create([
  'type'        => 'article',
  'title'       => 'Sample Node',
  'field_image' => [
    'target_id' => $file->id(),
    'alt' => 'Sample',
    'title' => 'Sample File'

For your information : Replace all node_save($node) calls with $node->save(), the same for node_delete(). Remove node_delete_multiple($ids) with entity_delete_multiple('node', $ids). Replace comment references with \Drupal\Core\Entity::save() and so on.  For more information check here