diff --git a/VoiceController.php b/VoiceController.php index b0a3f1c..b7837e3 100644 --- a/VoiceController.php +++ b/VoiceController.php @@ -1,4 +1,4 @@ -public function voice(Request $request){ + + +public function voice(Request $request) { + + // using validator() helper method will throw correct validation error + + validator ($request->all(),[ + 'question_id' => 'required|int|exists:questions,id', + 'value' => 'required|boolean', + ])->validate(); + + + // Assuming Voice model is associated with one Question model + + $voice = Voice::with('question') + ->where('question_id', $request->post('question_id') + ->where('user_id', auth()->id) + ->first(); + + if ($voice !== null && $voice->value !== $request->post('value')) { + $voice->update([ + 'value'=>$request->post('value') + ]); + + return response()->json([ + 'message'=>'Your voice has been updated' + ], 201); + } + + else if ($voice !== null && $voice->value == $request->post('value')) { + return response()->json([ + 'message' => 'Sorry you are not allowed to vote more than once' + ], 500); + } + else { + $voice->create([ + 'user_id' => auth()->id(), + 'question_id' => $request->post('question_id), + 'value' => $request->post('value') + ]); + + return response()->json([ + 'message'=>'Voting completed successfully' + ], 200); + } + +} + +// The modal function that shows the one to one association of Voice to Question Model + +public function question() + { + return $this->belongsTo(Question::class); + }