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

motinska94's avatar

I can't see where n+1 problem occurs

Error : n+1 query problem

My method :

    public static function employee_of_the_month($minus = 0)
    {
        $employee = EmployeeMonthlySales::query()
            ->where('month', month_substract($minus))
            ->where('year', get_year_by_sub_month($minus))
            ->orderBy('total', 'desc')
            ->first();
        return collect([
                'name' => $employee->employee->name,
                'total' => $employee->total
        ]);
    }

I'm calling this method 2 times from my controller, one for employee of the month for current month, and one for previous month. I'm getting a n+1 alert from a package I installed, it goes away when I remove the $employee variable and return the collection as string.

Ps : I obviously tried adding ->with('employee') and ->with('employee:id,name'), still shows n+1

0 likes
3 replies
Snapey's avatar
Snapey
Best Answer
Level 122

when creating collection you are accessing $employee->employee->name

therefore causing access to a model that has not been loaded

You should follow the guidance and add ->with('employee') to your query

1 like
motinska94's avatar

@Snapey Sorry about late response, I got sick.

I know I'm accessing the name through a relationship but I don't think it's supposed to cause an n+1 issue. Because I'm calling the method twice and at most there should be 4 queries -actually since I've tried ->with('employee') as well, so there should be only 2-

I guess I'll ignore it for now since I don't think there's a better approach for the task I'm going for. I mean I can write another method that'll get me the 2 employees that make most sales within past 2 months but I don't see a point for doing that, especially since this data is going to be cached for 24 hours.

Congratulations about the Hall of fame thing, you really deserve it!

soufyaneyassin's avatar

you can use Laravel Debugbar to see the number of queries being executed and identify the relationships causing the n+1 problem.

Please or to participate in this conversation.