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

catto's avatar
Level 1

How to skip data when doing query if left join is exists?

How to skip data when doing query if left join is exists?

I'm trying to get data. First I get the in and then join it with out data.

How to skip/remove data from query if the out data from left join is exists? I don't want my query to get the data if it the out data is exists.

Example Data:

   | id | in_out | work_hour_type | work_hour_start | work_hour_end | attendance_time | checkout_time | employee_id | company_id |
    | 1  | in     | Shift          | 20:00:00        | 08:00:00      |  19:50:00       | 01-03-2022    |  EMPLOYEE-1 | COMPANY-1  |  
    | 2  | out    | Shift          | 20:00:00        | 08:00:00      |  08:14:00       | 01-03-2022    |  EMPLOYEE-1 | COMPANY-1  | 
    | 3  | in     | Shift          | 20:00:00        | 08:00:00      |  08:14:00       | 01-03-2022    |  EMPLOYEE-2 | COMPANY-2  | 

EMPLOYEE-1 has both in & out data. So I want to ignore it and only get data where doesn't have out which is EMPLOYEE-2

Code:

$shift = Attendance::where('attendance.work_hour_type', 'Shift')
                    ->where('attendance.in_out', 'in')
                    ->whereColumn('attendance.work_hour_start', '>=', 'attendance.work_hour_end')
                    ->whereDateBetween('attendance.attendance_time', $yesterday, $today)
                    ->where('attendance.checkout_time', '>', now())
                    ->leftJoin('attendance as out', function ($join) {
                        $join->on('attendance.employee_id', '=', 'out.employee_id')
                            ->where('out.in_out', 'out')
                            ->where('out.work_hour_type', 'Shift')
                            ->whereDate('out.attendance_time', 'attendance.checkout_time');
                    })
                    ->where('attendance.attendance_location_id', $location->id)
                    ->where('attendance.company_id', $data->company_id)
                    ->groupBy('attendance.employee_id')
                    ->get();
0 likes
1 reply

Please or to participate in this conversation.