I am trying to programmatically attach a file to a node, using the media module now included in core as of Drupal 8.5.0.

I wrote this drush script to stub out the creation of a new file media content piece.


use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;
use \Drupal\media\entity\Media;

$file = file_save_data(uniqid(), 'public://test' . uniqid() . '.txt');

$drupalMedia = Media::create([
  'bundle' => 'file',
  'uid' => '0',
  'file' => [
    'target_id' => $file->id(),


When I navigate to the site's media at admin/content/media, I see my media listed:

enter image description here

But when I edit the piece of media, my text file is not attached to it:

enter image description here

There are no error messages in watchdog.

What am I missing? What do I need to do to attach the file to the media?

1 Answer 1


The key for file needed to be field_media_file instead of file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.