Files field in content representations

I generated content representations for a list of projects (pages):
projects.json.php:

$data = [];

foreach ($page->children()->listed() as $project) {

  $data[] = [
    'title' => $project->title()->value(),
    'coverimage' => $project->coverimage()->toFile(),
    'video' => $project->video()->toFile(),
    'category' => $project->category()->value(),
  ];

}

echo json_encode($data);

While my text fields are rendered correctly, the two files fields (coverimage, video) generate objects with two empty properties, content and translations:

[
  - {
      "coverimage": {
        "content": null,
        "translations": null
      },
      ...
  },
  ...
]

Any help how I get access to the file properties like url, alt, etc…?

You have to convert the object toArray()

'coverimage' => $project->coverimage()->toFiles()->toArray(),

returns me an object with some data, but I’m still not able to get data like alt-text and copyright I specified in my file blueprint.

Then use

'coverimage' => $project->coverimage()->toFile()->inventory(),

that should give you all data for a single file.

'coverimage' => $project->coverimage()->toFile()->inventory(),

returns an error:

Call to a member function inventory() on null

same error occurs with every other called function (like ->url() or ->alt()).

Well, you always have to make sure you have an object before you call any class member method (see basic OOP recipe), here you can use the null-safe operator instead of an if statement to keep the code shorter.

$project->coverimage()->toFile()?->inventory()

I’ve uploaded a file on every project and it gets rendered perfectly on my php templates so I don’t understand why there seems to be no object and the returned value is null ?

[
  - {
      "coverimage": {
        "value": null
      },
      ...
  },
  ...
]

Ok, sorry, my bad, the inventory() method doesn’t exist for files. I guess you best bet is probably to create a custom array with the data from the file that you need.