skip to Main Content

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?

3

Answers


  1. 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;
    }
    
    Login or Signup to reply.
  2. You can define Eloquent One to One relation like this :

    appModelsUser.php

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

    appModelsEmployee.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'],
      ]);
    }
    
    Login or Signup to reply.
  3. I believe this question is regarding phpmyadmin and not the relationships in laravel.

    When creating the table, is the migration using a forign key?

    For example something similar to this on your emoloyee table

    $table->foreignId('user_id')->references('id')->on('users');
    

    This is what creates a forign key in the database, rather than a relationship in laravel.

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