0
votes

I have a relationship between two models, User and Follower. User hasMany Follower, and Follower belongsTo User. In my followers table in the database I have two columns, follower_id and following_id. Both these columns refer to the id column in the users table.

My follower and users table

followers

      id
      follower_id
      following_id

 users
      id
      name
      username

User Model

public function followers(){
    return $this->hasMany('App\Follower', 'follower_id');
}

public function followings(){
    return $this->hasMany('App\Follower', 'following_id');
} 

Follower Model

 public function user(){
       return $this->belongsTo('App\User');
    }

In a test controller I am doing this:

$followed = Follower::find(2);

From here, I would like to select one of the columns, follower_id or following_id, and access the user that this particular row belongs to by using $followed->user->name. How would I go about that? Since I need to select a column before accessing, I am a little bit confused. What can I do to access the data I need?

1
Can you dd($followed) to check result instance and show here. - Kingo
Yes. I am currently echoing this variable as such: {{$followed}} and I get the row from the DB returned. I just realized, I have got two columns there that are 'follower_id' and 'following_id', both of which are pointing to the users table as foreign keys of the users table id column. I will revise my question accordingly - carlstrom96
Use this query to check $query = Follower::with('user')->findorFail(2). Then dd($query), you should see user instance in relation row. If not, show your User and Follower table and model here - Kingo
$query returns: "Call to a member function addEagerConstraints() on null". I have added those items to the question above - carlstrom96
I am missing return statements in my Follower model. I just realized that. Thank you for putting in the time and helping out though! Really appreciate that! - carlstrom96

1 Answers

0
votes

Your table should be :

followers

      id
      follower_id
      following_id
      user_id

 users
      id
      name
      username

In your Follower model :

public function user()
{
    return $this->hasMany(Follower::class, 'user_id');
}

In your User model :

public function follower()
{
    return $this->belongsTo(User::class, 'user_id');
}

Then you can query like this :

$follower = Follower::with('user')->findorFail(2);
$user_name = $follower->user->name;