I have an eloquent query, and inside it I have 2 condition. The first is when attendance_time == today
and second is attendance_time == yesterday
. I want to use that condition but I don't know how.
I've tried like code bellow, but still not working.
Attendance::where('employee_id', $request->employee_id)
->where('in_out', 'in')
->when('attendance_time' == Carbon::today(), function ($q) {
return $q->where('attendance_time', Carbon::today());
})->when('attendance_time' == Carbon::yesterday(), function ($q) {
return $q->where('attendance_time', Carbon::yesterday());
})->first();
Format for attendance_time
is Y-m-d H:i:s
CodePudding user response:
You can use whereDate, here is additional info. However, your query needs some improvement. If you use when it is like an if statement. It checks your condition and if it is true then add query inside of its function.
If you create something like that:
Attendance::where('employee_id', $request->employee_id)
->where('in_out', 'in')
->when($request->attendace_time, function ($q) {
return $q->where('attendance_time', Carbon::today());
})
That means if your request has attendace_time then add where query.
Or If you want to just filter todays attandees then you can use:
Attendance::where('employee_id', $request->employee_id)
->where('in_out', 'in')
->whereDate('attendance_time', Carbon::today()->format('Y-m-d'));
CodePudding user response:
You can use whereBetween
method:
use Carbon/Carbon;
...
Attendance::where('employee_id', $request->employee_id)
->where('in_out', 'in')
->whereBetween('attendance_time', [
Carbon::now()->subDay()->toDateString(),
Carbon::now()->toDateString()
])->first();