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
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Error :

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
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
Please or to participate in this conversation.