'Create a new instance of a Laravel model with children models

At the moment, whenever I need to create a new instance of a Laravel model that has child models, I need to create the model in the controller, then loop over all the children while still in the controller and attach them to the parent model. The model is capable of exporting itself to an array that includes its children, so you would think you would be able to import an array to create an model object as well.

Is it possible to pass an array to a Laravel model and have it automatically create its own children too?



Solution 1:[1]

Put a method on your model that accepts the array of child objects data and creates and associates them. Then you only need to create the main model and call the child create method on it.

class MyModel
{

    ...

    public function createChildren($childData)
    {
        //create and associate children
    }
}

class MyController
{
    ...
    public function create()
    {
        ...
        $myModel = MyModel::create($modelData);
        $myModel->createChildren($childData);
    }
}

Solution 2:[2]

This should works for you, you can send the array with model values and child values

public static function createWithChildren(array $values)
{
    // Set all the children ellements you can fill
    $childs = [ 
        'comments' => null,
        'links' => null 
    ];

    // Remove the values from childs and add it to another temp array
    foreach ($childs as $child => $values){
        if (Arr::has($values, $child)) {
            $childs[$child] = Arr::pull($values, $child);
        }
    }

    // Create model without the related values and save
    $model = new self();
    $model = $model->fill($values);
    $model->save();

    // After save, set all children values
    foreach (array_filter($childs) as $child => $values) {
        $model->$child()->create($values);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Julio PopĆ³catl