Home > Net >  How to add relationship between database table in Laravel
How to add relationship between database table in Laravel

Time:12-28

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?

CodePudding user response:

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'],
  ]);
}

CodePudding user response:

If you issue with creating the model using relationships. You can add user_id to data while creating

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'],
        'user_id' => $user->id
    ]);

    return $user;
}
  • Related