Laravel 5: How to saveMany() based on value

The save many method accepts an array of models, so just use a for loop for the $plateContainer's number_of_slots

$plateContainer = PlateContainer::create($data);

$containers = [];

// Need to add one to our number of slots because
// the $i count starts at one instead of zero.
$slots = $plateContainer->number_of_slots + 1;

for($i = 1; $i < $slots; $i++) {
    $containers[] =  new ContainerSlot([
        'plate_container_id' => $plateContainer->getKey(),
        'slot' =>  $i,
        'occuiped' => false,
    ]);
}

$plateContainer->containerSlots()->saveMany($containers);

Tags:

Php

Laravel