Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Eloïse's avatar

Best solution in order to execute multiple database insert in defined order

Hello, I'm creating a form when I submit I want to insert the posted datas in different tables in a defined order what is the best way to achieve this : 1 - insert a customer if he doesn't exists 2 - insert customer's enterprise if it does'nt exists 3 - insert the relation if customer does'nt exists 4 - insert the customer's reservation on a course

Thank you

0 likes
7 replies
tykus's avatar

What is preventing you writing the code in that order?

If you want to get creative, you can refactor to a Pipeline approach; but from this remove, I don't see the need as yet...

Eloïse's avatar

OK, so, simply chaining eloquent request is enough and a pipeline is maybe a bazooka to kill a fly ?

tykus's avatar

@Eloïse chaining; they will be separate queries?

Tray2's avatar

Simply

$modelOne = ModelOne::create();
$modelTwo = ModelTwo::create();

You can define the fields you need for each model in the create method by passing an array.

1 like
Eloïse's avatar

@Tray2 Thanks that was the underlying question because when I submit the form, I get an array of POST values, and after the validation I must assign some of them for a model and other to another. I hope that if ModelOne::create fail I get an exception ?

Tray2's avatar
Tray2
Best Answer
Level 73

@Eloïse Yes you would. The assignment would look something like this

$modelOne = ModelOne::create([
	'name' => $validData['name']
]);

$modelTwo = ModelTwo::create([
	'address' => $validData['address']
);
1 like

Please or to participate in this conversation.