Algolia can't access $page->parent()->images()

I’m defining fields in the Algolia plugin config, and I need to index some data from a page’s parent. This works just fine: 'parent' => function($page){ return (string)$page->parent(); }

But this gives me a “Call to a member function url() on null” error. 'image' => function($page){ $page->parent()->images()->first()->url(); }. The $page->parent()->images()->first()->url() code works just fine in a regular template.

Am I missing something? Why am I able to access the page’s parent’s title but not its images in this context?

Are you using this code without checking if the image exists? You have to do it like in the example:

image' => function($page) {
        // Returns the URL of the first image of the page
        // You should always make sure to return something here, even if there are no images, to avoid errors
        $image = $page->parent()->images()->first();
        return ($image)? $image->url() : null;
      }

I simplified my code a bit for the example. I’ve actually been using this code (with the same error).

'image' => function($page){ r($page->parent()->images()->first(), $page->parent()->images()->first()->crop(720,480,70)->url() ); }

I just tried the vanilla php example as you indicated and that works just fine. Now I’m confused—aren’t these two logically identical ways of solving the problem?

Either way—glad to have it working. Thanks for the help.

No, they are not. In your code, you pass two parameters to the r() function, but in your second parameter you call a method on an object that doesn’t exist; so PHP evaluates the parameter, before it is even passed to the function, therefore you can’t use the r() function like you do.

You could do something like this, however:

echo r($page->images()->first(), 'blue', 'green');

Thanks so much for articulating that important difference! Really appreciate the help.