Ashley Banks Ashley Banks - 2 years ago 125
PHP Question

Laravel - Inserting multiple items using one-to-many relationship

Is it possible to insert multiple values through a one-to-many relationship, so that the multiple values are saved with the foreign key.

So for example: I have an array of 'contributers' which a user can select to add to a project - upon saving I want these contributers to be referenced to the just saved project.

Trying the code below (the array is coming from $_POST['contributers'] which are checkboxes) - it saves the data, but doesn't attach the foreign key. I want to avoid having to use a loop and just be able to bulk insert all of these


Answer Source

You can use the createMany method (link to source)

$project = $this->project->find($project->id);

I also propose a small refactoring : one action per line and use of Input::get() instead of Input:only(), which is designed for other use cases.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download