I’m working with Laravel v10 and I have a users
table and each user has also another record at the members
table.
So in order to set up the One To One Relationship between these two Models:
User Model:
public function member()
{
return $this->hasOne(Member::class, 'mbr_usr_id', 'id');
}
Member Model:
public function user()
{
return $this->belongsTo(User::class, 'id', 'mbr_usr_id');
}
Then I tried dd(auth()->user()->member->mbr_name);
but didn’t return any result and showed null
!
However there is already a record at the members
table with mbr_usr_id
connected with id
of users
table.
So what’s going wrong here? How can I fix this issue?
This is the Migration of users
table:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('usr_name');
...
});
And this is the Migration of members
table:
Schema::create('members', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('mbr_usr_id')->nullable();
$table->foreign('mbr_usr_id')->references('id')->on('users')->onDelete('CASCADE');
});
2
Answers
You can change foreign key and owner key in the
belongsTo()
method. In your case ‘id’ and ‘mbr_usr_id’. This should work:You can read about it more at
https://laravel.com/docs/9.x/eloquent-relationships#one-to-many-inverse
try this
dd(auth()->user->member)
->user()
and->member()
returnBuilder
object, while->user
and->member
returnUser
andMember
model instances.