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?
dd($followed)to check result instance and show here. - Kingo$query = Follower::with('user')->findorFail(2). Thendd($query), you should see user instance inrelationrow. If not, show your User and Follower table and model here - Kingo