skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. try this dd(auth()->user->member)

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search