Programmatically create media file I'm trying to programmatically create a media file. Here's what I got so far:

$file_data = file_get_contents('http://www.africau.edu/images/default/sample.pdf');

$file = file_save_data($file_data, 'public://3010.pdf', FILE_EXISTS_REPLACE);

$media = Media::create([
  'bundle' =&gt; 'file',
  'uid' =&gt; '0',
  'field_media_file' =&gt; [
    'target_id' =&gt; $file-&gt;id(),
  ],
]);

$media-&gt;setName('Hello')
  -&gt;setPublished(TRUE)
  -&gt;save();


Unfortunately this returns me the following error and the media file doesn't get saved:


  Error: Call to a member function getSource() on null in Drupal\media\Entity\Media->getSource() (line 138 of core/modules/media/src/Entity/Media.php).


What am I doing wrong? How can I fix this error?
uid shouldn't be 0, just change 'uid' =&gt; '0' by 'uid'=&gt; \Drupal::currentUser()-&gt;id():

$file_data = file_get_contents('http://www.africau.edu/images/default/sample.pdf');
$file = file_save_data($file_data, 'public://3010.pdf', FILE_EXISTS_REPLACE);
$media = Media::create([
  'bundle'           =&gt; 'file',
  'uid'              =&gt; \Drupal::currentUser()-&gt;id(),
  'field_media_file' =&gt; [
    'target_id' =&gt; $file-&gt;id(),
  ],
]);
$media-&gt;setName('Hello')-&gt;setPublished(TRUE)-&gt;save();