/** * Store a newly created resource in storage. * * Interviews are submitted as sets of tags and responses to questionnaires. * * @return Response */ public function store() { $v = Validator::make(Request::all(), ['type' => 'required|string', 'questionSet' => 'required|string', 'recordedAt' => 'required', 'questions' => 'array', 'taggable' => 'array', 'location' => 'required|string', 'area' => 'required|string', 'houseno' => 'string']); if ($v->fails()) { return Response::json(['errors' => $v->errors()], 400); } $Date = Carbon::createFromTimeStamp(Input::get('recordedAt')); $interview = Interview::firstOrNew(['date' => $Date, 'interviewer_id' => Auth::user()->id]); $Questionnaire = Questionnaire::where('name', '=', Input::get('questionSet'))->first(); // important to fail here, you shouldn't be able to submit an interview for a questionnaire that doesn't exist if (!$Questionnaire) { return Response::json(['message' => 'questionnaire "' . Input::get('questionSet') . '" does not exist'], 400); } $interview->questionnaire_id = $Questionnaire->id; $interview->type = Input::get('type'); // similarly, area has to exist already $area = Area::where(['name' => Input::get('area')])->first(); if (!$area) { return Response::json(['message' => 'area "' . Input::get('area') . '" does not exist'], 400); } // although we can allow for dynamically adding new locations as they come in. $location = Location::firstOrCreate(['name' => Input::get('location'), 'area_id' => $area->id]); $interview->location_id = $location->id; if (Input::has('houseno')) { $interview->house_number = Input::get('houseno'); } $interview->save(); if (Input::has('questions') && $interview->type === 'interview') { foreach (Input::get('questions') as $response) { InterviewResponse::create(['question' => $response['question'], 'answer' => $response['answer'], 'interview_id' => $interview->id]); } } if (Input::has('taggable') && $interview->type === 'interview') { foreach (Input::get('taggable') as $list) { if (isset($list['id'])) { $this->saveTagsToQuestionnaire($list); } $TagList = new TagList(); $TagList->name = $list['name']; $interview->tagLists()->save($TagList); foreach ($list['tagged'] as $tag) { $TagList->tags()->save(Tag::create(['name' => $tag, 'tag_list_id' => $TagList->id])); } } } $interview->push(); return Response::json(Interview::with('responses')->find($interview->id), 200); }