Exemplo n.º 1
0
 public static function createFromInput(\Illuminate\Http\Request $input, $id = null, $save = true)
 {
     $module = parent::createFromInput($input, $id, $save);
     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
     // Register plants
     ////
     $inputPlants = $input->get('plant', []);
     $plantsById = [];
     foreach ($inputPlants as $plantId => $inPlant) {
         $plantsById[$plantId] = ['input' => $inPlant, 'model' => null];
     }
     $currentPlants = $module->plants;
     $module->plants()->detach();
     foreach ($currentPlants as $plant) {
         if (isset($plantsById[$plant->id])) {
             // plant updated
             $plantsById[$plant->id]['model'] = $plant;
         } else {
             $plant->delete();
         }
     }
     foreach ($plantsById as $plantId => $arrPlant) {
         if (is_null($arrPlant['model'])) {
             $arrPlant['model'] = Plant::find($plantId);
         }
         if (!$arrPlant['model']) {
             continue;
         }
         $module->plants()->save($arrPlant['model'], ['amount' => $arrPlant['input']['amount']]);
     }
     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
     // Register categories
     ////
     $inputCategories = $input->get('category', []);
     $categoriesById = [];
     foreach ($inputCategories as $categoryId => $inCategory) {
         $categoriesById[$categoryId] = ['input' => $inCategory, 'model' => null];
     }
     $currentCategories = $module->categories;
     foreach ($currentCategories as $category) {
         if (isset($categoriesById[$category->id])) {
             // category updated
             $categoriesById[$category->id]['model'] = $category;
         } else {
             $module->categories()->detach($category->id);
         }
     }
     foreach ($categoriesById as $categoryId => $arrCategory) {
         if (!is_null($arrCategory['model'])) {
             continue;
         }
         $arrCategory['model'] = Category::find($categoryId);
         if (!$arrCategory['model']) {
             continue;
         }
         $module->categories()->attach($arrCategory['model']);
     }
     return $module;
 }