/** * Store a newly created resource in storage. * * @return Response */ public function store() { $createanotherone = Input::only(['createanother']); //2. validate order fields $orderInput = Input::only(['specialinstruction', 'approval']); $orderValidator = Validator::make($orderInput, $this->rules()); $errors = []; if ($orderValidator->fails()) { $errors[] = $orderValidator->errors(); } //order Items $orderitemRules = $this->orderitemrules(); $orderItems = Input::get('orderitems'); //1. validate order items information foreach ($orderItems as $item) { $item['estimatedprice'] = preg_replace("/[^0-9\\.]/", "", $item['estimatedprice']); $item['estimatedtotal'] = preg_replace("/[^0-9\\.]/", "", $item['estimatedtotal']); $item['finalprice'] = preg_replace("/[^0-9\\.]/", "", $item['finalprice']); $item['finaltotal'] = preg_replace("/[^0-9\\.]/", "", $item['finaltotal']); $orderItemValidator = Validator::make($item, $orderitemRules); if ($orderItemValidator->fails()) { $errors[] = $orderItemValidator->errors(); } } if (count($errors)) { dd($errors); return Redirect::back()->withInput()->withErrors($errors); } //save order $newOrder = new Orders(); $newOrder->user_id = $this->user->id; $newOrder->specialinstruction = $orderInput['specialinstruction']; $newOrder->status = 1; $newOrder->save(); $error = 0; // save order items foreach ($orderItems as $item) { $orderItemObj = new OrderItems(['category_id' => $item['category'], 'vendor_id' => $item['vendor'], 'order_id' => $newOrder->id, 'name' => $item['name'], 'description' => $item['description'], 'quantity' => $item['quantity'], 'estimatedprice' => preg_replace("/[^0-9\\.]/", "", $item['estimatedprice']), 'estimatedtotal' => preg_replace("/[^0-9\\.]/", "", $item['estimatedtotal']), 'fixedprice' => preg_replace("/[^0-9\\.]/", "", $item['finalprice']), 'fixedtotal' => preg_replace("/[^0-9\\.]/", "", $item['finaltotal']), 'status' => 1]); if (!$newOrder->orderitems()->save($orderItemObj)) { $error++; } $approval = Approvals::find(5); dd($approval->orderItems()->attach($orderItemObj->id)); if ($orderItemObj->approval()->create(['orderitem_id' => $orderItemObj->id, 'approval_id' => 5, 'approval_user_id' => Input::get('approval')])->save()) { $error++; } //save the approval } if ($error) { //remove the order $newOrder->orderItems()->delete(); $newOrder->delete(); return Redirect::to('admin/orders')->withErrors(trans('message.msg_order_create_fail')); } if ($createanotherone) { return Redirect::to('admin/orders/create')->withSuccess(trans('message.msg_order_create_success')); } return Redirect::to('admin/orders')->withSuccess(trans('message.msg_order_create_success')); }