user391986
user391986

Reputation: 30886

Laravel Relationship error trying to call a relationship within the model

On Laravel "4.1.x-dev",

How can I call a method on a relation within the model? From the below example

public function userLink() {
  return $this->user->link;
} 

My function userLink gives me the error : Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

Also is there another way for me to access the linked user from Drawing with some kind of eager loading trick?

enter image description here

I have several different type of users. Each type of user has it's own table with an ID in each table that corresponds to the *ID** of the users table. In my Users model I have a method called ''link'' that performs a ''morphTo'' and gets me the correct user object.

class Drawing extends Eloquent {
    public function user() {
        return $this->belongsTo('User', 'user_id');
    }

    // this throws the relation error above, also I beleive this does two queries, anyway to improve this?
    public function userLink() {
        return $this->user->link;
    }
}

class User extends Eloquent {
    public function link() {
        return $this->morphTo('User', 'type', 'id');
    }
}

class Retailer extends Eloquent {
    public function user() {
        return $this->belongsTo('User', 'id');
    }
}

class Manufacturer extends Eloquent {
    public function user() {
        return $this->belongsTo('User', 'id');
    }
}

Upvotes: 1

Views: 3864

Answers (1)

The Alpha
The Alpha

Reputation: 146191

Try this instead:

Drawing::first()->user->link;

or this:

// Drawing model
public function user()
{
    return $this->belongsTo('User', 'user_id');
}

// Drawing model
// Requires above relation
public function userLink()
{
    return $this->user->link;
}

Then:

$ulink = Drawing::first()->userLink();

Also check the Defining An Accessor.

Update: Just make changes to your method like this (Create an accessor):

public function getUserLinkAttribute()
{
    return $this->user->link;
}

Upvotes: 3

Related Questions