Search code examples
phplaraveleager-loading

Laravel 5 Eager loading with a function


I have a function in my model (WeeshUser) that returns email if there are no Name or Surname for the user.

// RETURN EMAIL OR NAME
public function nameOrEmail() {
    $return = " - ";
    // Check for first name
    if ($this->first_name) {
        $return = $this->first_name;
        // Add lastname if exists
        if ($this->last_name) {
            $return .= " " . $this->last_name;
        }
    } elseif ($this->last_name) {
        // if only lastname exists
        $return = $this->last_name;
    } else {
        //else return email
        $return = $this->email;
    } 
    return $return;
}

I would like to call this function when eager loading from a controller ex:

$weeshReturn = WeeshShare::with('sender.nameOrEmail')->get();

The sender object is a WeeshUser object, and if run this without the .nameOrEmail it runs fine, but if run it like this I get an error

Call to a member function addEagerConstraints() on a non-object

Can this be done?


Solution

  • You get this error because Eloquent is assuming nameOrEmail is a relation to sender and expects it to return Illuminate\Database\Eloquent\Relations\Relation object, but you return a string from it.

    nameOrEmail is a normal method on the sender class and it does not to be eager loaded, you already eager load sender.

    What you can do instead is:

    $weeshReturn = WeeshShare::with('sender')->get();
    $weeshReturn->sender->nameOrEmail();