简体   繁体   中英

Saving Multiple Data into Database from Different Controllers - Laravel

I am have two different controllers, user and company . I want to save the data from user controller and company controller at the same time. Is it a good practice to combine the store method from company controller in the user controller?

User Controller

  $user = new User(array(
            'name'  => $request->get('name'),
             ));

            $user->save();

    $company = new Company(array(
            'name'  => $request->get('name'),
             ));

            $company->save();

If you have the relationship set up correctly you can:

$user = \App\User::create([
  "name" => $request->name,
  "company_id" => \App\Company::create([
    "name" => $request->name
  ])->id
]);

Assuming you have company_id in your users table, and inside your User model:

public function company() {
    return $this->hasOne(Company::class);
}

It would be fine to save both the company & user in the UserController. The best approach would be to use Eloquent Relations and wrapping both saves in a transaction.

\DB::transaction(function() {
    $user->save();
    $user->company()->save($company);
});

Or another approach:

$user->setRelation('company', $company)->push()

The magic of push() will save the User & Company in one-go.

Store the user and the company first

$user = new User();
$user->name = $request->name;
$user->save();
$company = new Company();
$company->name = $request->name;
$company->save();

then, look at your relation

if one user can have one company(in company's table has user_id)

$user->company()->save($company);
or
$company->user()->associate($user);

if one company can have one user(in user's table has company_id)

$company->user()->save($user);
or
$user->company()->associate($company);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM