public static function subscribe($id, Request $request) { $idsToInsert = []; $idsToUpdate = []; $idsToDelete = []; if ($request->has('id')) { $input = $request->all(); $idsToInsert = []; $idsToUpdate = []; foreach ($input['id'] as $key => $value) { if (!$value) { $lunch = Lunch::create(['user_id' => $id, 'name' => $input['name'][$key], 'meal1_id' => $input['meal1'][$key], 'meal2_id' => $input['meal2'][$key], 'garnish_id' => $input['garnish'][$key], 'salad_id' => $input['salad'][$key], 'drink_id' => $input['drink'][$key], 'price' => $input['price'][$key]]); $lunch->additions()->sync($input['additions'][$key] ? explode(',', $input['additions'][$key]) : []); Sub::create(['user_id' => $id, 'lunch_id' => $lunch->id, 'day' => $input['day'][$key], 'quantity' => $input['quantity'][$key]]); $idsToInsert[] = (string) $lunch->id; } else { $lunch = Lunch::findOrFail($value); $lunch->price = $input['price'][$key]; $lunch->save(); $sub = Sub::where('lunch_id', $value)->firstOrFail(); $sub->quantity = $input['quantity'][$key]; $sub->save(); $idsToUpdate[] = $value; } } $idsToDelete = Sub::where('user_id', $id)->whereNotIn('lunch_id', array_merge($idsToUpdate, $idsToInsert))->get()->lists('lunch_id'); Lunch::whereIn('id', $idsToDelete)->delete(); Sub::whereIn('lunch_id', $idsToDelete)->delete(); } else { $lunchToDelete = Sub::where('user_id', $id)->get()->lists('lunch_id'); Lunch::whereIn('id', $lunchToDelete)->delete(); Sub::whereIn('lunch_id', $lunchToDelete)->delete(); } return ['insert' => $idsToInsert, 'update' => $idsToUpdate, 'delete' => $idsToDelete]; }
/** * Store a newly created resource in storage. * * @param Request $request * * @return Response */ public function store(Request $request) { $this->validate($request, ['name' => 'required']); $item = Lunch::create($request->all()); $this->saveInfo($item, $request); Flash::success("Запись - {$item->id} сохранена"); return redirect(route('admin.lunchs.index')); }
/** * Run the database seeds. * * @return void */ public function run() { DB::table('lunchs')->delete(); for ($i = 0; $i < count($this->items); $i++) { $row = array_combine(['name', 'description', 'meal1_id', 'meal2_id', 'garnish_id', 'salad_id', 'drink_id', 'price', 'image'], $this->items[$i]); $lunch = Lunch::create($row); $lunch->additions()->attach([1, 2, 3]); } }