Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

php - how to condition same time data to insert and update in laravel

I will try If on today's date, any row insert Then update value use id And if not any row today's date Then insert a new row. but the problem is update value is working but not insert a new row message is "Trying to get property 'Date' of non-object"

public function present($id){
  $user = User::find($id);
  $date = date('Y-m-d');
  $id = $user->id;
  $Attendance= Attendance::where('User_A_ID','=',$id)->first();
  
  if($Attendance->Date == $date){
        $Attendance->A_sts = '0';
        $Attendance->Date = $date;
        $Attendance->User_A_ID = $user->id;
        $Attendance->save();
  } else {
        $Attendance= new Attendance();
        $Attendance->A_sts = '0';
        $Attendance->Date = $date;
        $Attendance->User_A_ID = $user->id;
        $Attendance->save();
  }
  return back();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If I understand you correctly you want to update the existing attendance that belongs to the user or create a new attendance if the user does not have one.

You can simplify your code:

public function present($id)
{
    $user = User::findOrFail($id);
    $date = date('Y-m-d');

    $Attendance = Attendance::firstOrNew(['User_A_ID' => $user->id, 'Date', $date]);

    $Attendance->User_A_ID = $user->id;
    $Attendance->Date = $date;
    $Attendance->A_sts = '0';
    $Attendance->save();

    return back();
}

Use findOrFail to check if the user exists, and then use firstOrNew to retrieve the existing attendance for today or create a new instance of it, this way you can get rid of your if statement.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...