├── README.md └── VoiceController.php /README.md: -------------------------------------------------------------------------------- 1 | # Laravel Challenge: API Controller - Voices 2 | 3 | This is a Controller code that needs to be improved, in whatever way possible. 4 | 5 | Author's question: "how to make clean code to this code" 6 | Source: [Youtube comment](https://www.youtube.com/watch?v=kc8Ks3ElGmM&lc=Ugw_mwNX5Als7nfFvat4AaABAg) 7 | 8 | This repository is not a full Laravel project, just that one Controller file. 9 | Your task is to improve the code, by submitting a Pull Request. 10 | 11 | --- 12 | 13 | ## Rules: How to perform the task 14 | 15 | I will be expecting a Pull Request to the `main` branch, containing **all** fixes with completely working project. 16 | 17 | If you don't know how to contribute a PR, here's [my video with instructions](https://www.youtube.com/watch?v=vEcT6JIFji0). 18 | 19 | **Important**: I will NOT merge the Pull Request, only comment on it, whether it's correct or not. 20 | 21 | With my limited time, I will probably personally review first 10 Pull Requests, all the others will still get "karma points" by doing a good job to help the author. 22 | 23 | If you have any questions, or suggestions for the future challenges, please open an Issue. 24 | 25 | Good luck! 26 | 27 | -------------------------------------------------------------------------------- /VoiceController.php: -------------------------------------------------------------------------------- 1 | public function voice(Request $request){ 2 | $request->validate([ 3 | 'question_id'=>'required|int|exists:questions,id', 4 | 'value'=>'required|boolean', 5 | ]); 6 | 7 | $question=Question::find($request->post('question_id')); 8 | if (!$question) 9 | return response()->json([ 10 | 'status'=>404, 11 | 'message'=>'not found question ..' 12 | ]); 13 | if ($question->user_id==auth()->id()) 14 | return response()->json([ 15 | 'status' => 500, 16 | 'message' => 'The user is not allowed to vote to your question' 17 | ]); 18 | 19 | //check if user voted 20 | $voice=Voice::where([ 21 | ['user_id','=',auth()->id()], 22 | ['question_id','=',$request->post('question_id')] 23 | ])->first(); 24 | if (!is_null($voice)&&$voice->value===$request->post('value')) { 25 | return response()->json([ 26 | 'status' => 500, 27 | 'message' => 'The user is not allowed to vote more than once' 28 | ]); 29 | }else if (!is_null($voice)&&$voice->value!==$request->post('value')){ 30 | $voice->update([ 31 | 'value'=>$request->post('value') 32 | ]); 33 | return response()->json([ 34 | 'status'=>201, 35 | 'message'=>'update your voice' 36 | ]); 37 | } 38 | 39 | $question->voice()->create([ 40 | 'user_id'=>auth()->id(), 41 | 'value'=>$request->post('value') 42 | ]); 43 | 44 | return response()->json([ 45 | 'status'=>200, 46 | 'message'=>'Voting completed successfully' 47 | ]); 48 | } --------------------------------------------------------------------------------