Cast Entry to appropriate type to access fields and functions in module Newbie to Craft CMS. I am trying to send a push notification to an app when an entry of specific type (NewsItem) is saved, and I'm doing so via a Craft Module. I got this code snippet from another StackExchange question, and I have changed it a bit to implement it according to my needs:

        Craft::$app-&gt;elements-&gt;on(Elements::EVENT_AFTER_SAVE_ELEMENT, function(ElementEvent $event) {

            // Make sure it's an entry.
            if ($event-&gt;element instanceof craft\elements\Entry) {
                $entry = $event-&gt;element;

                // Check if it's in the section you care about
                if ($entry-&gt;sectionId == 1) {
                    // Do your custom logic

                        if(isset($entry-&gt;photo))
                            $image_name = $entry-&gt;photo-&gt;getUrl();
                        else
                            $image_name = 'http://img.youtube.com/vi/' . $entry-&gt;youtubeVideoCode . '/0.jpg';


I'm getting this error:

Calling unknown method: craft\elements\db\AssetQuery::getUrl()


I may be wrong, but I'm assuming I have to cast $entry to (NewsItem) somewhere in the code to access the getUrl() function? How and where do I do that?

Thanks in advance for your help.
The actual answer is mostly unrelated to your question, but I wanted to provide some context, first!

Entry Types don't get their own PHP classes. All Entries are just instances of the craft\elements\Entry class, distinguished by their section ($entry-&gt;getSection()) and type ($entry-&gt;getType()) values.

If you need to check the section and type of your entry, you can compare against the sectionId and typeId properties. Keep in mind that these IDs may be different, across environments, so it's better to use the handle and keep it in sync with your project.yml:

if ($entry-&gt;getSection()-&gt;handle == 'mySectionHandle' &amp;&amp; $entry-&gt;getType()-&gt;handle == 'myEntryTypeHandle') {
  // Your logic!
}


Ok, now on to the error you're seeing!

Calling unknown method: craft\elements\db\AssetQuery::getUrl()


This is actually telling you that the accessed field/property (photo) returns an object that doesn't have a getUrl() method.

Unless relational field data is eager-loaded, accessing its property will return an ElementQuery (in your case, an AssetQuery), prepped to return the related Elements.

So, before accessing methods on the expected value (an Asset Element), you have to execute the query:

$photo = $entry-&gt;photo-&gt;one();

if ($photo) {
  // At least one photo was attached! You can safely access the Asset object's properties + methods:
  $url = $photo-&gt;getUrl();
} else {
  // Set a default:
  $url = 'https://...';
}