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

afoysal's avatar

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 ?

0 likes
11 replies
Snapey's avatar

You store clock in and clock out on the same row of the database?

1 like
Snapey's avatar

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?

b-rian's avatar

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]);
1 like
afoysal's avatar

Thanks @snapey . Do you have any suggestion ? Yes, $request->clock_in is correct.

afoysal's avatar

Thanks @b-rian . I am trying to use your Query. But it is not working. Thanks.

Snapey's avatar

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));
1 like
Snapey's avatar

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]);

1 like
tisuchi's avatar

@afoysal

I personally also tell you to follow @snapey 's verbose approach that is more organized and meaning.

1 like
Snapey's avatar
Snapey
Best Answer
Level 122

"not working" is always so helpful

1 like

Please or to participate in this conversation.