PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, December 30, 2021

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

 December 30, 2021     laravel     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing