The replicate() method in Laravel is used to create a copy of a model instance, but it does not automatically copy the relationships. However, you can manually replicate the relationships after you've replicated the model. Here's how you can do it for your "Plan" model and its related "Task" models, as well as the "Action" models related to each "Task".
// Find the original plan
$originalPlan = Plan::with('tasks.actions')->find($planId);
// Replicate the plan
$newPlan = $originalPlan->replicate();
$newPlan->push(); // Save the new plan
// Loop over each task and replicate it
foreach ($originalPlan->tasks as $task) {
$newTask = $task->replicate();
$newTask->plan_id = $newPlan->id; // Set the foreign key to the new plan's id
$newTask->push(); // Save the new task
// Now replicate each action for the task
foreach ($task->actions as $action) {
$newAction = $action->replicate();
$newAction->task_id = $newTask->id; // Set the foreign key to the new task's id
$newAction->push(); // Save the new action
}
}
In this example, we first retrieve the original plan and eager load its tasks and actions. We then replicate the plan and save it. After that, we loop through each task, replicate it, update its plan_id to associate it with the new plan, and save it. For each task, we also loop through its actions, replicate each one, update the task_id to associate it with the new task, and save it.
Please note that you'll need to adjust the foreign key names (plan_id and task_id) if they are different in your models. Also, ensure that any unique constraints on your tasks or actions are handled appropriately when replicating them (e.g., if you have a unique constraint on a name or slug, you'll need to modify these to be unique for the new copies).