If I understand this correctly you want the top seller for each month, current and previous one, right ?
If that's the case then first you need to grab the max totals for each month
$maxSales = EmployeeMonthlySales::query()
->select(['year','month', DB::raw('max(total) as total')])
->whereIn(
DB::raw("CONCAT(month,'-',year)"),
[$datetime_now->format('n-Y'), $datetime_prev->format('n-Y')]
)
->groupBy(['year', 'month'])
;
So then you use that as derived table to join with monthly sales and get the employee_id
$topSellers = EmployeeMonthlySales::query()
->select(['employee_id','max_sales.*'])
->joinSub($maxSales, 'max_sales', function($join) {
$join
->on('monthly_sales.year','=','max_sales.year')
->on('monthly_sales.month', '=', 'max_sales.month')
->on('monthly_sales.total', '=', 'max_sales.total');
})
->get()
;
That should work.
BTW, this doesn't guarantee you'll get only two records because there is the small chance of two -or more- employees being at the top of a month
