Correct Query I am doing clock in and clock out. In this regard I would like to insert clock out time of user where the clock in time is already inserted. My query is like below.
DB::table('clocks')
->where('user_id', Auth::user()->id)
->latest('created_at ')->first()
->update(array('clock_out' => $request->clock_in));
Is it correct query ?
You store clock in and clock out on the same row of the database?
@snapey , yes, I am trying to do so. Thanks.
So you need to find the last row for the user where the clockout time is null and then update it. Otherwise you risk overwriting a previous clock out.
Suppose the user has not clocked in? What is the rule for handling that?
Your update uses $request->clock_in is that the correct field?
It looks good. I have just done something similar. I think the only thing different is a clock_out is null check. This is after I already checked if the user is clocked in, so I know he has a database record with a null clock_out field.
DB::table('clocks')
->where('user_id', auth()->id())
->whereNull('clock_out')
->latest()
->update(['clock_out' => $request->clock_out]);
Thanks @snapey . Do you have any suggestion ? Yes, $request->clock_in is correct.
Thanks @b -rian . I am trying to use your Query. But it is not working. Thanks.
as suggested, check that clockout is null
DB::table('clocks')
->where('user_id', Auth::user()->id)
->whereNull('clock_out')
->latest('created_at ')->first()
->update(array('clock_out' => $request->clock_in));
Personally, I would probably be more verbose
$lastClock=DB::table('clocks')
->where('user_id', Auth::user()->id)
->whereNull('clock_out')
->latest('created_at ')
->first();
if(empty($lastClock)) {
// throw exception, could not find correct record
}
$lastClock->update(['clock_out' => $request->clock_in]);
@afoysal
I personally also tell you to follow @snapey 's verbose approach that is more organized and meaning.
@snapey Sorry your solution is not working. Thanks,
"not working" is always so helpful
Please sign in or create an account to participate in this conversation.