From e637a3ab5fff84966a754cf26627bed8896308a0 Mon Sep 17 00:00:00 2001 From: "M.Imran-Invozone" Date: Fri, 30 Jul 2021 14:21:12 +0500 Subject: [PATCH] code refector by Muhammad Imran --- VoiceController.php | 55 ++++++++++++++++++++++----------------------- 1 file changed, 27 insertions(+), 28 deletions(-) diff --git a/VoiceController.php b/VoiceController.php index b0a3f1c..75510f7 100644 --- a/VoiceController.php +++ b/VoiceController.php @@ -1,48 +1,47 @@ public function voice(Request $request){ + + // THIS VALIDATION SHOULD BE IN REQUEST CLASS // $request->validate([ 'question_id'=>'required|int|exists:questions,id', 'value'=>'required|boolean', ]); - $question=Question::find($request->post('question_id')); - if (!$question) - return response()->json([ - 'status'=>404, - 'message'=>'not found question ..' - ]); - if ($question->user_id==auth()->id()) - return response()->json([ - 'status' => 500, - 'message' => 'The user is not allowed to vote to your question' - ]); + $question = Question::find($request->question_id); + if (!$question){ + return $this->response(404, 'not found question'); + } + + if ($question->user_id == auth()->id()){ + return $this->response(500, 'The user is not allowed to vote to your question'); + } //check if user voted - $voice=Voice::where([ - ['user_id','=',auth()->id()], - ['question_id','=',$request->post('question_id')] - ])->first(); - if (!is_null($voice)&&$voice->value===$request->post('value')) { - return response()->json([ - 'status' => 500, - 'message' => 'The user is not allowed to vote more than once' - ]); - }else if (!is_null($voice)&&$voice->value!==$request->post('value')){ + $voice = Voice::where(['user_id' => auth()->id(), 'question_id' => $request->question_id])->first(); + if(!$voice){ + + if($voice->value===$request->value){ + return $this->response(500, 'The user is not allowed to vote more than once'); + } + $voice->update([ 'value'=>$request->post('value') ]); - return response()->json([ - 'status'=>201, - 'message'=>'update your voice' - ]); - } + return $this->response(201, 'update your voice'); + } + $question->voice()->create([ 'user_id'=>auth()->id(), 'value'=>$request->post('value') ]); + return $this->response(200, 'Voting completed successfully'); +} + +public function response($status = 200, $message = '') +{ return response()->json([ - 'status'=>200, - 'message'=>'Voting completed successfully' + 'status' => $status, + 'message' => $message ]); } \ No newline at end of file