Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 5 additions & 40 deletions VoiceController.php
Original file line number Diff line number Diff line change
@@ -1,44 +1,9 @@
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'
]);
}
public function voice(VoiceRequest $request, Question $question){
$validated = $request->validated();

$question->voice()->create([
'user_id'=>auth()->id(),
'value'=>$request->post('value')
$question->voice()->updateOrCreate([
['user_id' => auth()->user()->id]
'value' => $validated['value']
]);

return response()->json([
Expand Down
13 changes: 13 additions & 0 deletions VoicePolicy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace App\Policies;

class VoicePolicy
{
use HandlesAuthorization;

public function vote(User $user, Question $question)
{
return $question->user_id != $user->id;
}
}
33 changes: 33 additions & 0 deletions VoiceRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class VoiceRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
$question = $this->route('question');

return auth()->user()->can('vote', $question);
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'question_id' => 'required|int|exists:questions,id',
'value' => 'required|boolean',
];
}
}