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']);
My Answer:
This code snippet is correct for saving multiple related models in Laravel. The `createMany` method allows you to create multiple related models at once.
In this case, you first create the company with the name using `Company::create($request->safe()->only(['name']))`, and then you use the `createMany` method on the `contacts` relationship of the company to create multiple contacts related to that company.
Make sure that your `Company` model has the `contacts` relationship defined correctly in order for this code to work.
Rate this post
3 of 5 based on 8930 votesComments