From 3a5071302a9a71a3f897b74f1d88e5462a2a6eae Mon Sep 17 00:00:00 2001 From: tkadahal Date: Fri, 30 Jul 2021 14:22:51 +0545 Subject: [PATCH 1/2] Changes made --- VoiceController.php | 57 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/VoiceController.php b/VoiceController.php index b0a3f1c..45c8fe0 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->hasOne(Question::class); + } From 311598b5fb2d428d715dd15b4ea32f6899f2b93e Mon Sep 17 00:00:00 2001 From: Tika Dahal <69100170+tkadahal@users.noreply.github.com> Date: Fri, 30 Jul 2021 15:01:39 +0545 Subject: [PATCH 2/2] Update VoiceController.php --- VoiceController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/VoiceController.php b/VoiceController.php index 45c8fe0..b7837e3 100644 --- a/VoiceController.php +++ b/VoiceController.php @@ -97,5 +97,5 @@ public function voice(Request $request) { public function question() { - return $this->hasOne(Question::class); + return $this->belongsTo(Question::class); }