Fetching files from a field in a controller

I have a page that fetches a subpage in it’s controller via URL:

$curProjekt = $site->find('projekte')->children()->filterBy('slug', $urlProj)->listed();

I can easily fetch it’s corresponding images like this:

$galerie = $curProjekt->images()->sortBy('sort', 'asc');

However, this way the sort order from the file-field galerie is not used. If I fetch the image files via the field in the template like this, it works and sort order is like in the panel:

$curProjekt->galerie()->toFiles()

However if I use the same code directly in the controller, I always get an error Call to a member function galerie() on null. Why is this not working in the controller?

Hi, can you post your full code from the controller please?

Maybe you forgot to return the variable at the end of it?

  return [
    'curProjekt' => $curProjekt,
  ];

Thanks, but it’s returned. Here’s the full controller code:

<?php

return function ($page, $kat, $site, $urlKat, $urlProj) {
    
    $kats = $site->find('kats-projekte')->children();
    
    $projekte = $page->children()->listed();
		if ($urlKat != null && $kats->find('kats-projekte/' . $urlKat)) {
			$projekte = $projekte->filterBy('kats', $urlKat, ',');
		}
		
		$curProjekt = null;
		$galerie = null;
		if ($urlProj != null) {
			$curProjekt = $site->find('projekte')->children()->filterBy('slug', $urlProj)->listed();
			$galerie = $curProjekt->images()->sortBy('sort', 'asc');
			/* $galerie = $curProjekt->galerie(); */
		}
		

		
		return [
			'projekte' => $projekte,
			'kats' => $kats,
			'urlKat' => $urlKat,
			'urlProj' => $urlProj,
			'curProjekt' => $curProjekt,
			'galerie' => $galerie
		];

};

$galerie is only set when there is an url actuyll requesting the subpage.

Can you post where $urlProj comes from?

That’s coming from a route in the config.php:

	'routes' => [
			[
					'pattern' => 'projekte/(:any)/(:any)',
					'action' => function ($urlKat, $urlProj) {
							if ($page = page('projekte/' . $urlKat . '/' . $urlProj)) {
									return $page;
							} else {
								return page('projekte')->render([
									'urlKat' => $urlKat,
									'urlProj' => $urlProj
								]);
							}
					}
			],

Ups, sorry I think I found the difference why it’s working in the template, but not in the controller. I had this in the template:

$curProjekt = page($curProjekt);

Moving it into the controller made it work, phew :)

Thanks for looking into this!