PHP Laravel get all question from question's table base on the foreign Key of vote's Table
If I can I would like to be able to get all "voted questions" the questions authenticated user have voted. and return in a json format.
I want to get the questions referenced from vote's table "question_id".
Questions Table:
id(PK)| title | description | created_at | updated_at
Question Model hasMany votes
class Question extends Model { public function votes() { return $this->hasMany(Vote::class, 'question_id'); } }
Votes Table:
id(PK) | answer_id(FK) | question_id(FK) | user_id(FK)
Vote Model belongsTo a question
class Vote extends Model { public function question() { return $this->belongsTo(Question::class, 'question_id'); } }
Filter Method: Will return all the voted question alongside the votes (I only want the questions)
public function filtered()
{
$user_id = Auth::user()->id;
$votes = Vote::with('question')->where('user_id', $user_id)->get();
$votes->makeVisible('question');
return response()->json($votes);
}
I was able to get all the "voted questions" through Vote Model. but I would like to get only the question.
Current Result : votes with voted questions
[
{
"id": 1,
"question_id": 1,
"answer_id": 2,
"user_id": 1,
"question": {
"id": 1,
"title": "a question this user voted",
}
},
{
"id": 2,
"question_id": 2,
"answer_id": 3,
"user_id": 1,
"question": {
"id": 2,
"title": "another question this user voted",
}
}
]
Desired Result : only voted questions
[
{
"id": 1,
"title": "a question this user voted",
},
{
"id": 2,
"title": "another question this user voted",
}
]
is this possible? if not, any advice will be appreciated
Answer
Solution:
You can get all votes for a user like so:
User.php
And you can get all questions from votes like so:
Vote.php
Then you should be able to access all these relationships, and pluck the relevant values.