Home > Enterprise >  Laravel how to save multiple related models?
Laravel how to save multiple related models?

Time:11-22

My form posting this data

{
  "name": "Company Name1",
  "contacts": [ 
    {
      "name":"John Doe",
      "phone":"123123"
    },
    {
      "name":"John Doe 2",
      "phone":"123123"
    }
  ]
}

I want to create a company with the name and then for each contact in contacts new contact relation which is related to this company.

Do you guys have any idea about how can I do that with createMany or something like that ?

Solution

Guys, I realized that I forgot to send specific required data with the form after I fix that I realized that I'm able to store data with this code

$company->contacts()->createMany($request->contacts);

and this is the last version of the code

$arr = $request->safe()->only(['contacts']);
$company = Company::create($request->safe()->only(['name']));
$company->contacts()->createMany($arr['contacts']);

CodePudding user response:

You can bulk insert records using insert method in laravel

Create a new company record and then use that company's id to insert record in contact table

$company = new Company;
$company->name = "Your Company Name";
$company->save();
$data = [
           [ "name"=>"John Doe", "phone"=>"123123","company_id"=> $company->id ],
           [ "name"=>"John Doe", "phone"=>"123123","company_id"=> $company->id ]
        ];
Contact::insert($data);

CodePudding user response:

Multiple ways to do that. On way would be to use the saveMany Method:

$company = new Company;
$company->name = "Your Company Name";
$company->save();

$company->contacts()->saveMany([
    new App\Models\Contact([ "name"=>"John Doe", "phone"=>"123123","company_id"=> $company->id ],),
    new App\Models\Contact([ "name"=>"John Doe", "phone"=>"123123","company_id"=> $company->id ],),
]);

https://laravel.com/docs/5.5/eloquent-relationships#the-save-method

CodePudding user response:

I solved the situation apparently I could just store the data like this

$company->contacts()->createMany($request->contacts);

But when sending the data, I forgot to send the required input, so it was not working because of that.

  • Related