Retrieving Model Virtual Attribute

In a Project in which we assign a Contact, I wish to display the contact’s information (Fullname). So in the Project Model I have

public function getContact()
    return $this->hasOne(ClientsContacts::className(), ['ContactId' => 'ContactId']);

and in the Contact Model I have

public function getFullName()
    $output = $this->FirstName;
    if( isset($this->LastName) && trim($this->LastName) != '' ){
        $output .= ' '.$this->LastName;
    return $output;

In my View I was trying to retrieve the attribute by doing


This worked in a general sense, but it erred in the case where someone had deleted the contact from the database.

Now, yes, I have to implement proper referential integrity between tables, but what is the right way to retrieve such an attribute and not have the view fail because of such an issue. Is the following the best approach or should I be doing something differently?

    $contact = $model->Contact;
        echo $contact->Fullname;

Thank you for your help.

Hi @DBCreator,

I would define a virtual attribute in Project model.

public function getContactName()
    return ($this->contact) ? $this->contact->fullName : '';

And in the view:

// $model Project
echo $model->contactName;