Perhaps writing the code to save topics could be written in an action ? Would it be a good idea ?
Big form - How to separate nested controller actions (save/update) ?
Hello,
The title seems to be contradictory : separate some nested things.
I explain.
I have an application where companies can handle trainings and courses schedule.
A training has many units, each unit has many topics, and each topic has one or many trainers. To save all these datas, I have these tables : trainings, units, topics, topic_trainer.
For convenience, I have chosen to save and edit units in one unique form where the use can rename the unit (name, hours_number), add / remove topics (name, hours_number, text_color, background_color), add / remove trainers associated with topics.
To save a unit, I have therefore a method like this one (for the moment the trainers are not managed in the app, I have to work on this) in my TrainingUnitController.
public function store(UnitRequest $request, Training $training)
{
$unit = new Unit;
$unit->fill($request->all());
$unit->training_id = $training->id;
$unit->save();
foreach ($request->topics as $item) {
$topic = new Topic;
$topic->fill($item);
$topic->unit_id = $unit->id;
$topic->training_id = $training->id;
$topic->save();
}
}
That means that this method not only saves a unit but also topics (and later in a pivot table the trainers attached to the topics).
It works fine, but is there another way to handle the saving / updating of big forms with nested datas saved in different tables ?
I mean there is perhaps a way to save the topics at a different place in the code so that the TrainingUnitController does not have to save topics. But the problem is that the data come from the post request and sent to the controller.
Thanks for your help.
Vincent
@vincent15000 It isn't what I meant :)
public function store(UnitRequest $request, Training $training)
{
$unit = new Unit;
$unit->fill($request->all());
$unit->training_id = $training->id;
$unit->save();
$topics = collect($request->topics)->map(fn($t) => [
'unit_id' => $unit->id,
'field' => 'value'
// ...
]);
Topic::insert($topics); // Will run only one query
}
Please or to participate in this conversation.