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

Maison012's avatar

Larvel foreach N+1 problem with query

Hello, i am working with relations table for moment and i need to query between them. So i have a table team with some skills , and i am biulding a report to count all teams with same skills, so this work:

$skills = Skill::get();
            $countSkill = [];
            $skillField = [];
            foreach($skills as $skill) {
                $skillField[] = $skill->skills_name;
                $countSkill[] = Team::whereRelation('skills', function($query) use($skill) {
                    $query->where('skills_name', $skill->skills_name);
                })->count();
            }

But on clockwork database query i see too much query i think

Skill	
SELECT count(*) AS aggregate FROM `teams` WHERE EXISTS (SELECT * FROM `skills` INNER JOIN `skill_team` ON `skills`.`id` = `skill_team`.`skill_id` WHERE `teams`.`id` = `skill_team`.`team_id` and (`skills_name` = 'androind developer'))

Skill	
SELECT count(*) AS aggregate FROM `teams` WHERE EXISTS (SELECT * FROM `skills` INNER JOIN `skill_team` ON `skills`.`id` = `skill_team`.`skill_id` WHERE `teams`.`id` = `skill_team`.`team_id` and (`skills_name` = 'designer'))

Skill	
SELECT count(*) AS aggregate FROM `teams` WHERE EXISTS (SELECT * FROM `skills` INNER JOIN `skill_team` ON `skills`.`id` = `skill_team`.`skill_id` WHERE `teams`.`id` = `skill_team`.`team_id` and (`skills_name` = 'web developer'))

I have 8 skills for now and i see 8 different query. Is there any method to avoid this N+1 problem using this foreach query?

0 likes
6 replies
Maison012's avatar

@Snapey I am trying to use something like this

foreach($skills as $skill) {
                $skillField[] = $skill->skills_name;
            }
            $countSkill = Team::withCount(['skills' => function ($query) use($skill) {
                $query->where('skills_name', $skill->skills_name);
            }])->get();
            dd($countSkill->skills_count);

But i get 0 as result. And i want to count all team based on skills

Snapey's avatar

@Leon012 you are still putting the query in a loop. Did you check the linked docs?

SilenceBringer's avatar

@leon012

$skills = Skill::withCount('teams')->get();

dd($skills);

now every Skill model should have teams_count attribute, which is count of associated teams

Really, it's as easy as first example in the link @snapey provided to you

$posts = Post::withCount('comments')->get();

Maison012's avatar

@SilenceBringer Now i see. It was very easdy but i think i missunderstand the documentation couse i was trying to query Team model

Please or to participate in this conversation.