Is there any method to avoid this N+1 problem
yes, never put db query inside a loop
https://laravel.com/docs/9.x/eloquent-relationships#counting-related-models
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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?
Is there any method to avoid this N+1 problem
yes, never put db query inside a loop
https://laravel.com/docs/9.x/eloquent-relationships#counting-related-models
Please or to participate in this conversation.