Search code examples
laraveleloquentsql-updatestorelaravel-5.7

Laravel(New user) : user store function to update() and save() . If not exist save() else Update()


  public function store(Request $request)
    {
        //

        /*$request->validate([
                    'user_id'=>'required',
                    'time_in'=>'required',
                     'log_date'=>'required',
        ]);*/
        //dd($_POST);

        $attendance = new Attendance([
            'user_id' => $request->get('user_id'),
            'location' => $request->get('location'),
            'time_in' =>  date('h:i:s'), /*$request->get('time_in'),*/
            'log_date' => date('Y-m-d')  /* $request->get('log_date')*/

        ]);

       $user=Attendance::where('user_id', $request->get('user_id') && 'log_date', date('Y-m-d'))->first();

if($user == null) {

    $attendance->save();
    return  redirect()
        ->back()
        ->with('success', $request->get('user_id').':  You have clocked in successfully!');

}else{

   /* Attendance::where('user_id', $request->get('user_id') && 'log_date', date('Y-m-d'))->update(
        ['time_out' => date('Y-m-d')]
    );*/

   $attendance->update(['time_out'=> date('Y-m-d')]);

    return  redirect()
        ->back()
        ->with('success', $request->get('user_id').':  You have clocked Out!');


}

Solution

  • Thanks to everyone that contributed, This worked

    public function store(Request $request) {

        $user= Attendance::where(['user_id'=> $request->get('user_id'), 'log_date' => date('Y-m-d')] )->first();
       // $existingLog = Attendance::find($user->id);
    
    
        if(!$user){
            Attendance::create(['user_id'=> $request->get('user_id'), 'location'=>$request->get('location'),
                'time_in'=>date('h:i:s'), 'log_date'=>date('Y-m-d')]);
    
            return  redirect()
                ->back()
                ->with('success', $request->get('user_id').':  You have clocked in successfully!');
    
        }
    
    
        $user->update(['time_out'=> date('h:i:s')]);
    
    
        return  redirect()
            ->back()
            ->with('success', $request->get('user_id').':  You have clocked Out!');
    

    }