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();
}
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.
Related
I am trying to store a historical data through API from front-end(flutter). Below are the controller in laravel. When I ran my code in postman, it supposed to work, since the message "suksess add data" does appear when I sent a request and the date_checkIn, time_checkIn are all recorded as shown here https://paste.pics/f31592f51f63a5f77af77b0c0ad1e555. However, when I check in my database, the date_checkIn, time_checkIn, and location_checkIn column is NULL and only staff_id, created_at, updated_at column is recorded . As I try and repeat the request in postman but change location_checkIn, a new record appear in the attendance_record table showing the same result but now there are 2 of the same staff_id and also created_at and updated_at column is recorded.
I want to store the record everytime the user clock in from front-end(flutter). How do I fix this ?
public function userClockIn(Request $r)
{
$result = [];
$result['status'] = false;
$result['message'] = "something error";
$users = User::where('staff_id', $r->staff_id)->select(['staff_id', 'date_checkIn', 'time_checkIn', 'location_checkIn'])->first();
$mytime = Carbon::now();
$time = $mytime->format('H:i:s');
$date = $mytime->format('Y-m-d');
// Retrieve current data
$currentData = $users->toArray();
// Store current data in attendance record table
$attendanceRecord = new AttendanceRecord();
$attendanceRecord->fill($currentData);
$attendanceRecord->save();
$users->date_checkIn = $date;
$users->time_checkIn = $time;
$users->location_checkIn = $r->location_checkIn;
$users->save();
$result['data'] = $users;
$result['status'] = true;
$result['message'] = "suksess add data";
return response()->json($result);
}
You still need field id when updating the user data. You may change some of your select statement by add 'id' into it :
$users = User::where('staff_id', $r->staff_id)->select(['id', 'staff_id', 'date_checkIn', 'time_checkIn', 'location_checkIn'])->first();
After that, go to your AttendanceRecord model, add field id into guarded.
protected $guarded = ['id'];
After that, you can try it to run the endpoint again. It should be updated.
But if you don't want to add guarded into your AttendanceRecord model, you should change your code when retrieve current data into:
$currentData = [
"staff_id" => $users->staff_id,
"date_checkIn" => $users->date_checkIn,
"time_checkIn" => $users->time_checkIn,
"location_checkIn" => $users->location_checkIn,
];
Hello I'm just having a little trouble with a function, to explain it first it's supposed to get the difference between two dates and take that number then subtract it from a field on the database and it works well or so I thought until I noticed that whatever date I put it always returns only the number 5
Leave Model
protected $dates = ['from', 'to'];
public function numberOfDays()
{
$datesx =Leave::where('user_id', auth()->user()->id)
->first();
$from =$datesx->from;
$to =$datesx->to;
$datetime1 = new DateTime($from);
$datetime2 = new DateTime($to);
$interval = $datetime1->diff($datetime2);
$days = $interval->format('%a');//now do whatever you like with $days
return $days;
}
User Model
public function leaveBalance()
{
$leave =new Leave;
$daysUsed= $leave->numberOfDays();
// $daysUsed = $this->leaves->map->numberOfDays()->sum();
// return $this->leave_days_granted - $daysUsed;
$days_granted = User::where('id', auth()->user()->id)
->first();
$leave_days_granted = $days_granted->leave_days_granted;
return $leave_days_granted - $daysUsed;
}
public function hasAvailableLeave()
{
return $this->leaveBalance() > 0;
}
public function leaves()
{
return $this->hasMany(\App\Leave::class);
}
Leave Controller
public function store(Request $request)
{
$this->validate($request,[
'from'=>'required',
'to'=>'required',
'description'=>'required',
'type'=>'required'
]);
$data=$request->all();
$data['user_id']=auth()->user()->id;
$data['message']='';
$data['status']=0;
$leave =Leave::create($data);
/** update users table with leaveBalance() return value*/
//get logged in user id
$user_id=auth()->user()->id;
//get the returned value from User model method
$leave_balance = new User;
// $leave_balance->leaveBalance();
// dd($leave_balance->leaveBalance());
// die();
DB::table('users')
->where('id', $user_id)
->update(['leave_days_granted' => $leave_balance->leaveBalance()]);
By only returns the number 5 I mean is that every time a leave is requested/stored it subtracts -5 from the field leave_days_granted but it's supposed to subtract the difference between the two dates that is given in the leave table, fields "from" and "to" which stores the date from and to a specific date
In my user model, I have the following code
public function profile()
{
return $this->hasOne(UserProfile::class);
}
In profile model,
public function user()
{
return $this->belongsTo(User::class);
}
The create method is working, But when I try to update the profile with following code, It is creating a new profile and doesn’t update the profile information.
$profile = new UserProfile();
$profile->dob = '1999-03-20';
$profile->bio = 'A professional programmer.';
$profile->facebook = 'http://facebook.com/test/1';
$profile->github = 'http://github.com/test/1';
$profile->twitter = 'http://twitter.com/test/1';
$user = User::find($userId);
$res = $user->profile()->save($profile);
What is the correct method to update in One to One Relationship ?
I fixed it using push method. Here is the code.
$user = User::find($userId);
$user->name = "Alen";
$user->profile->dob = '1999-03-20';
$user->profile->bio = 'A professional programmer.';
$user->profile->facebook = 'http://facebook.com/test/1';
$user->profile->github = 'http://github.com/test/1';
$user->profile->twitter = 'http://twitter.com/test/1';
$user->push();
You're doing right, however i could suggest a little improvement
You may use the following
$user = User::with('profile')->findOrFail($userId);
if ($user->profile === null)
{
$profile = new UserProfile(['attr' => 'value', ....]);
$user->profile()->save($profile);
}
else
{
$user->profile()->update(['attr' => 'value', ....]);
}
you are using save method to save new record. use update query
//controller
$userObj=new User();
if(!empty($userId) && $userId!=null){
$userObj->updateByUserId($userId,[
'dob' = '1999-03-20';
'bio' = 'A professional programmer.';
'facebook' = 'http://facebook.com/test/1';
'github' = 'http://github.com/test/1';
'twitter' = 'http://twitter.com/test/1';
]);
}
//model
function updateByUserId($userId,$updateArray){
return $this->where('user_id',$userId)->update($updateArray);
}
I have a code where I use map to create a new collection of high scores.
The problem I have is that it overrides the default user collections. Which is not my intention.
Here is the code
$users = Users::all();
$highscore = $users->map(
function ($user) {
$calls = $user->calls->filter(
function ($call) {
$date = Carbon::parse($call->datetime)->format("Y-m-d");
$today = Carbon::now()->format("Y-m-d");
return $date == $today;
}
);
return [
'id' => $user->id,
'duration' => $calls->sum('duration'),
];
}
);
If i dump the first user after getting all the users I get the first user. Like this.
$users = Users::all();
dd($users->first());
If I dump the first user after the high score map. I get all Calls from that user which is another model. Which means that the users collection has been modified. Like this.
$highscore = $users->map(
function ($user) {
$calls = $user->calls->filter(
function ($call) {
$date = Carbon::parse($call->datetime)->format("Y-m-d");
$today = Carbon::now()->format("Y-m-d");
return $date == $today;
}
);
return [
'id' => $user->id,
'duration' => $calls->sum('duration'),
];
}
);
dd($users->first()):
Any idea on how to handle this behaviour?
The map function returns an array of [[$userId => $duration], ...]. What you want to do is to order your users by the sum of their calls.
I believe that, in order to do that easily, you should add to your User model:
public function getTodayCallSum() {
return $user->calls->filter(function($call) {
$date = Carbon::parse($call->datetime)->format("Y-m-d");
$today = Carbon::now()->format("Y-m-d");
return $date == $today;
})->sum('duration');
}
And then edit your query:
$users = User::all();
$firstUser = $users->sortBy('todayCallSum')->first();
I haven't tested this code, but I think it should help you towards the right direction.
I try to take the facebook information of a user in my databade. I'm in the UserIdentity to control the athentification of the user and i created this method.
<?php
public function insertFbUser()
{
$user = new User();
$user->fbId = $this->username['id'];
$user->username = $this->username['username'];
$user->email = $this->username['email'];
$user->password = $this->password;
$profile = new Profile();
$profile->first_name = $this->username['first_name'];
$profile->last_name = $this->username['last_name'];
$profile->birthday = strtotime($this->username['birthday']);
$profile->sex = $this->username['gender'];
$profile->fb_updated_time = strtotime($this->username['updated_time']);
$profile->fb_verified = $this->username['verified'];
$profile->fb_educationJson = json_encode($this->username['education']);
$profile->fb_workJson = json_encode($this->username['work']);
var_dump($user->save());
var_dump($profile->save());
}
the var_dump() show me this
boolean true
boolean false
Both models were created with the GII module. I try to only put one prile attribute at a time and it doesn't work too...
There is my DB : http://pastebin.com/u5CNKj9M
Thank you for your help!
print_r($profile->getErrors());
(Update)To get user id after saving:
$user->save();
$user_id = $user->id