From d275b8e40bd8ee3abdd751e10bd2ee84fbc25000 Mon Sep 17 00:00:00 2001 From: Ed Paul Date: Fri, 30 Jul 2021 17:52:55 +0800 Subject: [PATCH] my own implementation and arrangement --- VoiceController.php | 70 ++++++++++++++++++++++----------------------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/VoiceController.php b/VoiceController.php index b0a3f1c..b60476b 100644 --- a/VoiceController.php +++ b/VoiceController.php @@ -1,48 +1,48 @@ -public function voice(Request $request){ +public function voice(Request $request) +{ $request->validate([ - 'question_id'=>'required|int|exists:questions,id', - 'value'=>'required|boolean', + 'question_id' => [ 'required', 'integer', '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()) + $question = Question::findOrFail($request->question_id); + + if ($question->user_id == auth()->id()) { return response()->json([ - 'status' => 500, - 'message' => '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')) { + 'status' => 500, // left this one here, because the original author might have a purpose for this + 'message' => __('The user is not allowed to vote to your question') + ], 500); + } + + //check if user voted + $voice = $request->user() + ->voices() // In these scenario, I prefer to use hasMany voices relationship from the User model instead + ->where('question_id', $request->question_id) + ->first(); + + if ($voice && $voice->value == $request->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->update([ - 'value'=>$request->post('value') - ]); + 'status' => 500, // left this one here, because the original author might have a purpose for this + 'message' => __('The user is not allowed to vote more than once') + ], 500); + } + + if ($voice && $voice->value != $request->value) { + $voice->update([ 'value' => $request->value ]); + return response()->json([ - 'status'=>201, - 'message'=>'update your voice' - ]); + 'status' => 201, + 'message' => __('Your voice has been updated') + ], 201); } $question->voice()->create([ - 'user_id'=>auth()->id(), - 'value'=>$request->post('value') + 'user_id' => auth()->id(), + 'value' => $request->value ]); return response()->json([ - 'status'=>200, - 'message'=>'Voting completed successfully' + 'status' => 200, + 'message' => __('Voting completed successfully') ]); -} \ No newline at end of file +}