-2

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');
});
Pouya
  • 114
  • 1
  • 8
  • 36

2 Answers2

0

You can change foreign key and owner key in the belongsTo() method. In your case 'id' and 'mbr_usr_id'. This should work:

/**
 * Get the post that owns the comment.
 */
public function post()
{
    return $this->belongsTo(Post::class, 'foreign_key', 'owner_key');
}

You can read about it more at https://laravel.com/docs/9.x/eloquent-relationships#one-to-many-inverse

tripleee
  • 175,061
  • 34
  • 275
  • 318
Payam Aero
  • 11
  • 1
0

try this dd(auth()->user->member)

->user() and ->member() return Builder object, while ->user and ->member return User and Member model instances.

AlexandrX
  • 806
  • 8
  • 18