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

VinayPrajapati's avatar

Dynamic relation query

User::with('tournament')->whereHas('tournament', function ($q) use ($pegiYear) {
            $q = $q->where('status', 1);
			// if tournament is 'type' = 'private' add sub query here ("type" => 'column name', private/public is value of column)
			return $q;
});
0 likes
3 replies
lbecket's avatar

Are you asking how to include a sub-query only when the tournament type = 'private'?

You can construct your queries dynamically by assigning the various pieces to a $query variable--and you can construct it conditionally--but you would have to already know the value of type in order to pass that value to the condition.

VinayPrajapati's avatar

@lbecket

if type is private then i want show only invited user , and if type is public it's show all user.

User::with('tournament', 'invitations')->whereHas('tournament', function ($q) use ($pegiYear) {
            $q = $q->where('status', 1);
			// if tournament is 'type' = 'private' add sub query here ("type" => 'column name', private/public is value of column)
			return $q;
});

how i add condition in callback!

lbecket's avatar

@VinayPrajapati You're asking that a value contained in a query's result be used to conditionally build that same query, which is impossible.

I don't know anything about your schema, but I'd venture to say that there are probably a number of ways to achieve the desired result. You could run an initial query to get the type and then conditionally define a subsequent query. You could write a query to pull back all users and then filter the results based on the returned type. Maybe your data structure would allow for a table join to produce the necessary filtering... you haven't offered any context.

Again, there are likely numerous ways to achieve the desired dataset, but you can't do something conditionally when those conditions are produced by the results of the very query that you're attempting to build.

Please or to participate in this conversation.