I have 3 table: tasks
, users
, group
, and a pivot table group_user
.
A task has user_id
, group_id
A group_user pivot table has user_id
, group_id
I want to query the tasks if the task belongs to a group of the user.
I don’t want tasks from groups that the user doesn’t belong to.
What I have so far:
public function index()
{
$userId = Auth::user()->id;
return TaskResource::collection(
Task::
latest()
->whereHas('group', function($query) use($userId) {
$query->where('group_id', '=', $userId); // = is wrong
})
->get()
);
}
This gives me empty results, I tried to think about it but my head hurts
2
Answers
Ive not tested this but i imagine you could nest the where has and use something like this in your whereHas block:
You want to get the tasks that are related to the group (or groups) of a user.
I supposed the relation name between the user table and the group table is ‘users’, in the Group model.