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

Stucks's avatar

Query Builder - Searching records by a many-to-many relationshop

Hi All,

I have 2 models, kids and guardians linked by a many to many relationship.

I need to retrieve all records from the kids table that are related to any id in a given array of guardians.

I'm currently using the query below (which works, it just seems rather janky). Does anybody have suggestions to improve it?

if($request->filled('guardians')) {
	$guardians = $request->guardians;
	$c = 1;

	foreach($guardians as $guardian) {
		if($c == 1) {
			$query->whereHas('guardians', function ($q) use ($guardian) {
				$q->where('guardian_id', $guardian);
			});
		} else {
			$query->orWhereHas('guardians', function ($q) use ($guardian) {
				$q->where('guardian_id', $guardian);
			});
		}
		$c++;
	}
}
0 likes
3 replies
bugsysha's avatar
bugsysha
Best Answer
Level 61

Assuming that the $guardians variable is an array of valid ID's.

if ($request->filled('guardians')) {
    $guardians = $request->guardians;

    $query->whereHas('guardians', function ($q) use ($guardians) {
        $q->whereIn('id', $guardians); // Note that I've changed `guardian_id` to `id` and that depends on your database structure so if this doesn't work try changing it back to `guardian_id`
    });
}
Stucks's avatar

Ahhh... I knew it had to be something as simple as that! I still needed to use guardian_id in the whereIn() . But other than that, perfect.

thanks!

bugsysha's avatar

You are very welcome. Thanks for the "Best Answer".

Please or to participate in this conversation.