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');
}
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
Try to specify keys for hasOne and belongsTo method as below:
$this->hasOne('Profile', 'foreign_key', 'local_key');
$this->belongsTo('User', 'foreign_key', 'local_key');
Look also on one to one relation: https://laravel.com/docs/6.x/eloquent-relationships#one-to-one
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With