/** * Store a newly created resource in storage. * * @return Response */ public function store(Request $request) { $this->validate($request, ['dist_plan_id' => 'required|numeric']); $distPlanID = $request->input('dist_plan_id'); // Get distPlan try { // validate if dist_plan is already realized $distPlan = DistPlan::with('details')->where('is_realized', '=', 0)->findOrFail($distPlanID); } catch (ModelNotFoundException $e) { $execMsg = "Distribution plan is not found or has been realized."; return redirect('circulation/distribution-realization')->with('errMsg', $execMsg); } // The big work starts here // dist_plan exist, and not yet realized, // generate exact data for dist_realize from dist_plan (manually assign) $distReal = new DistRealize(); $distReal->distribution_plan_id = $distPlanID; $distReal->edition_id = $distPlan->edition_id; $distReal->print = $distPlan->print; $distReal->gratis = $distPlan->gratis; $distReal->distributed = $distPlan->distributed; $distReal->stock = $distPlan->stock; $distReal->date = $distPlan->publish_date; $distReal->print_number = $distPlan->print_number; $distReal->save(); // make dist_plan.is_realized set to 1 $distPlan->is_realized = 1; $distPlan->save(); // generate exact data for dist_realize_details from dist_plan_details foreach ($distPlan->details as $distPlanDet) { $distRealDet = new DistRealizeDetail(); $distRealDet->dist_real_id = $distReal->id; $distRealDet->agent_id = $distPlanDet->agent_id; $distRealDet->save(); } // done return redirect('circulation/distribution-realization'); }