Relationship between table is not working

Viewed 87

I have two tables user and profile. Profile table had user_id as foreign key. I have related the two tables.

In tinker I can see that relation is made but in code its not fetching the details from other table.

I have also tried

return $this->belongsTo('User::class');

User Model

public function profile() {
    return $this->hasOne('Profile');
}

Profile Model

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

I see two things that are not completely right.

In tinker to obtain the profile of user insert this lines:

$user = User::find([user_id]);

And then :

$user->profile();

If you want to associate the ::class you should use:

return $this->belongsTo(User::class);

If you want to use the string association should use:

return $this->belongsTo('App\User');
return $this->hasOne('App\Profile');

Another tip is every time you change a controller you have to close and open tinker again

Related