Home > Blockchain >  How to insert data from one form in different database table in Laravel
How to insert data from one form in different database table in Laravel

Time:12-13

I am new to Laravel. I want to register the account so I have one form that has the details about the username, email, password, company name, and other company details. I got 2 tables in my database. Table 1 is the user table which is used to store the user details to log in like userID, email, password, and companyID (from table 2). Table 2 is the company table that stores company details. Table 2 has companyID, companyName, and so on. I want to ask how can I use one form to save my data in two different tables.

Here is the code from RegisterController

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

}

CodePudding user response:

First You Need To Insert In Company Table Then User Table Like This .

protected function create(array $data)
{
   $company=Company::create([
  'companyName'=>$data['companyName']
    ]);
    User::create([
        'username' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'companyID'=>$company->id
    ]);
   
  
}

CodePudding user response:

Laravel has a very elegant solution for this. First you have to set the relations between both models. As it happens, your example can now cover both directions. That's why I now assume: a user can have many companies and a company only one user.

This means that in the user model you set the relation

protected function companies() {
    return $this->hasMany(Company::class);
}

And in the Company Model you set this method:

protected function user() {
    return $this->belongsTo(User::class);
}

Then in your controller, service etc. you can call the following:

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

$company = [
    'companyName' => 'fooBar',
];

$user->companies()->save($company);

Link to the doc: https://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models

  • Related