Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Jakub003's avatar

How to make nested whereHas eloquent query

This is is the current query

 $userId = 1;
 $projectId = 1;

        return Kanban::where('project_id', $projectId)
                      ->whereHas('cards.users.user', function ($query) use ($userId) {
                          $query->where('user_id', $userId);
                      })
                      ->get();

I am trying to find -> all kanbans where project id = 1 -> where also has cards associated with it, that also have a user with id of 1

I am not getting any errors, just a null result.

I tried to follow along this example

$packages = Package::where('alias','like',"%$search%")
  ->whereHas('product.membership.club.user', function ($q) use ($user) {
    $q->whereId($user->id);
  })->get();

Not sure what I messed up, any help is much apprciated

0 likes
5 replies
Sinnbeck's avatar

Use debugbar to see the actual query. Maybe that will help you spot the error. Paste it here if you need help

Jakub003's avatar

I installed debugbar just now but it just shows a blank page, i think bc this is an API thing

in postman getting the same thing

is there other tools I could use to find this?

Sinnbeck's avatar

@Jakub003 ah ok. It can be a bit tricky to find the query when using ajax. Quick fix. Copy the query to a test route in web.php and run it in the browser. The query should now be easy to find under the queries tab

1 like
AlexSteele's avatar

it may be helpful to define the query as a variable called $results and then die/dump/debug that variable to see if it is indeed null. such as ddd($results) - and you could also try getting the count of that and then dd($count) to see how many returns come back from the query

1 like
Jakub003's avatar
Jakub003
OP
Best Answer
Level 7

For anyone that might stumble upon this in the future. He is an example of the nested queries

return Project::where('id', $projectId)
                      ->with(['kanbans' => function($query ) use ($userId){
                                  $query->whereHas('cards.users', function ($query) use ($userId) {
                                          $query->where('user_id', $userId);
                                  })
                                  ->with(
                                    'cards.users',
                                    'cards.tags.tag',
                                    'cards.column'
                                  )
                                  ->withCount('cards')
                                  ->with(['cards' => function($query){
                                          $query->withCount(['links','comments','tasks']);
                                      }]);
                              }])
                      ->with('tags')
                      ->firstOrFail();

    });

Please or to participate in this conversation.