Reputation: 13
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();
}
Upvotes: 0
Views: 1035
Reputation: 8252
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.
Upvotes: 1