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

noblemfd's avatar

Laravel Query Duplicates record twice

I am using Laravel-5.8 for this Query:

    $published_goalss = DB::table('hr_employees AS e')
                ->join('hr_employees AS em','em.employee_code','=','e.line_manager_id')
                ->join('hr_departments AS d','e.department_id','=','d.id')
                ->join('hr_employees AS eh','eh.employee_code','=','d.dept_head')
                ->join('hr_employees AS eb','eb.employee_code','=','d.hr_business_partner_id')
                ->join('appraisal_goals AS ag','ag.company_id','=','e.company_id')
                 ->select(
                    'e.employee_code as staff_id',
                    DB::raw('CONCAT(e.first_name, " ", e.last_name) AS full_name'),
                    DB::raw('IF(e.gender_code = 0, "Female", "Male") AS gender'),
                    'e.email as official_email',
                    DB::raw('CONCAT(eh.first_name, " ", eh.last_name) AS hod_name'),
                    DB::raw('CONCAT(eb.first_name, " ", eb.last_name) AS hrbp_name'),
                    DB::raw('(CASE WHEN ag.is_approved = 3 THEN "Approved" WHEN ag.is_approved = 2 THEN "Not Approved" WHEN ag.is_approved = 1 THEN "Awaiting Approval" ELSE "Draft" END) AS goal_status')
             )
                ->whereIn('e.employee_code', $publishedgoals)
                ->where('e.company_id', $userCompany)
                ->where('e.hr_status', 0) 
            ->distinct()
            ->get();

Initially it duplicates 4 times, but when I added

 ->distinct()  ->get();

it reduces the duplication to just two.

I dealyy the query should give me 2 records, but it is giving me 4 records.

How do I resolve this.

Thanks

0 likes
1 reply
bobbybouwmann's avatar

Well, you fetch a lot of data because of all the joins. If you only want two results you need to group the items by a certain value. Probably you need to group by one of the joined tables to make this work.

Please or to participate in this conversation.