Thursday, December 30, 2021

[FIXED] How to add relationship between database table in Laravel

Issue

I am new to Laravel. I want to do like this when user register the account, the details will save into 2 database table. Based on the image given below, I want to link the relationship between id with user_id:

enter image description here

So when I go to phpmyadmin, I click at user_id it will redirect me to see the user table details based on the id.

Here is my code:

protected function create(array $data)
{
  $user= User::create([
        'username' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

    $employee= Employee::create([
        'username' => $data['name'],
        'email' => $data['email'],
    ]);

    return $user;
}

Does anyone know how to do that?


Solution

You can define Eloquent One to One relation like this :

app\Models\User.php

public function employee()
{
   return $this->hasOne(Employee::class, 'user_id', 'id');
}

app\Models\Employee.php

protected $fillable = ['user_id','username','email'];

Now change your function to :

protected function create(array $data)
{
  $user = User::create([
        'username' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
  ]);

  $user->employee()->create([
      'username' => $data['name'],
      'email' => $data['email'],
  ]);
}


Answered By - sta

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.