forked from LaravelDaily/Laravel-Challenge-API-Voice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
VoiceController.php
48 lines (44 loc) · 1.42 KB
/
VoiceController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public function voice(Request $request){
$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'
]);
//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->update([
'value'=>$request->post('value')
]);
return response()->json([
'status'=>201,
'message'=>'update your voice'
]);
}
$question->voice()->create([
'user_id'=>auth()->id(),
'value'=>$request->post('value')
]);
return response()->json([
'status'=>200,
'message'=>'Voting completed successfully'
]);
}