skip to Main Content

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


  1. Ive not tested this but i imagine you could nest the where has and use something like this in your whereHas block:

    
    $query->whereHas('user', function($q2) use ($userId) {
        $q2->where('user_id', $userId);
    });
    
    Login or Signup to reply.
  2. 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.

    $userId = auth()->id();   
    
    $tasks = Task::latest()
                       ->whereHas('group', function($query) use ($userId) {
                            $query->whereHas('users', function($query) use ($userId) {
                                $query->where('user_id', $userId);
                            });
                        })
                        ->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search