Home > Software design >  Laravel 9 createMany() Child Tables When Parent is Created
Laravel 9 createMany() Child Tables When Parent is Created

Time:07-09

I'm working on a gardening app for indoor/outdoor home growers. A run has many cultivars and a cultivar belongs to the run.

When a user creates a new run, they enter how many cultivars (plants) are in the run. The below works when the data is hard coded, but I want the total number of cultivars created based on the amount the user enters in the run field. I know an array needs to be created, but I couldn't figure that part out.

public function createRun()
{

    $run = Run::create([
        'tenant_id' => 1,
        'name' => $this->name,
        'cultivars' => 2
    ]);

    $run->cultivars()->createMany([
        ['run_id' => $run->id, 'name' => $run->name . ' ' . 1],
        ['run_id' => $run->id, 'name' => $run->name . ' ' . 2],
    ]);

    return;
}

CodePudding user response:

You can use for to repeat many create() calls as required:

$run = Run::create([
    'tenant_id' => 1,
    'name' => $this->name,
    'cultivars' => 2
]);


$numberToCreate = $run->cultivars;

for ($i=1; $i <= $numberToCreate; $i  ) { 
    $run->cultivars()->create([
        ['name' => $run->name . ' ' . $i],
    ]);
}

An alternative that uses the createMany() method instead:

$numberToCreate = $run->cultivars;

$dataToInsert = [];

for ($i=1; $i <= $numberToCreate; $i  ) { 
    $dataToInsert[] = ['name' => $run->name . ' ' . $i];
}

$run->cultivars()->createMany($dataToInsert);

The ->create() and ->createMany() methods do not require you to set 'run_id' => $run->id as this is handled automatically (assuming you've set up your Eloquent relationships correctly).

As an alternative, you might also be able to use Events to automatically create the required cultivars after the created event fires for the Run model.

  • Related