Deducting the total leave when the leave request is approved - php

I have column total leave in table user and column days taken and status in table leave. I tried to deduct the total leave with the leave days taken when the leave is approved but it is not updated. I've tried with this code.
This function is for the applicant to apply for leave.
public function store(Request $request){
$dateFrom = Carbon::createFromFormat('Y-m-d', $request->date_from);
$dateTo = Carbon::createFromFormat('Y-m-d', $request->date_to);
$days_taken = $dateFrom->diffInDays($dateTo)+1;
if($request->leave_id == 1){
if($days_taken > auth()->user()->total_annual){
return redirect()->route('admin.leaverequest.create')->with('error', 'Leave exceed');
}
}
else{
return redirect()->route('admin.leaverequest.index')
->with('success', 'Leave Application Submitted');
}
Application::create([
'user_id'=>auth()->user()->id,
'leave_id'=>$request->leave_id,
'date_from'=>$request->date_from,
'date_to'=>$request->date_to,
'days_taken'=> $dateFrom->diffInDays($dateTo)+1,
]);
return redirect()->route('admin.leaverequest.index')
->with('success', 'Leave Application Submitted');
}
This is the function for approve/rejecting the leave request.
public function approval(Request $request, $id){
$leaverequest = Application::find($id);
if($leaverequest->status = $request->approve){
$leaverequest->save();
return redirect()->back();
}
elseif($leaverequest->status = $request->reject){
$leaverequest->save();
return redirect()->back();
}
}
This function is for the calculation to deduct the total leave everytime if the leave request is approved. If not, the total leave will stay as it is.
public function leaveBalance(Request $request, $id){
$leaverequest = Application::all();
$days_taken = $request->days_taken;
$annual_balance = User::find($id);
if($request->status == 1){
$annual_balance->total_annual = $annual_balance->total_annual - $days_taken;
$annual_balance->save();
return redirect()->route('home');
}
}
The other functions seems to function well except for the leaveBalance function. I've tried using this code but also didn't work.
auth()->user()->total_annual = auth()->user(->total_annual - $days_taken;
auth()->user()->save();

First of code looks fine , but if you getting error or not updating record then i suggests to debug your code first that all variables have values like $annual_balance = User::find($id); did you get data in this? and if you get all things then try to store $annual_balance->total_annual in one variable and then subtract code from variable.
function leaveBalance(Request $request, $id){
$leaverequest = Application::all();
$days_taken = $request->days_taken;
$annual_balance = User::find($id);
if($request->status == 1){
$total_annual = $annual_balance->total_annual;
$annual_balance->total_annual = $total_annual - $days_taken;
$annual_balance->save();
return redirect()->route('home');
}
}
// Or you can try using DB if above not work don't forget to add Use DB on top of Controller.
$affected = DB::table('users')
->where('id', $id)
->update(['total_annual' => $total_annual]);

You could also try this
I would say return a single total_annual (total_annual refers to the total leave field in the users table) for a certain user from the user table and note the keyword value() in the query which indicates one value.
$annual_balance variable store a total annual leave and $days_taken store the number of leave days taken and do some calculation as below to set the total annual which is the remaining total annual leave after days taken
$annual_balance->total_annual = $annual_balance - $days_taken;
public function leaveBalance(Request $request, $id){
$days_taken = $request->days_taken;
$annual_balance = User::where('user_id', $id)->select('total_annual')->value('total_annual');
if($request->status == 1)
{
$annual_balance->total_annual = $annual_balance - $days_taken;
$annual_balance->save();
return redirect()->route('home');
}
}

Related

Laravel query builder get records for user on log in

I've got a Laravel API and have a function that runs when a user logs in, when they log in, I want to find associated domains linked to their account and get domains based on whether a notification has gone out for domain expiry or SSL expiry.
My code is working, but what I've noticed, is it's finding ALL domains regardless of the user ID, and I just want to get the domains for the user that logged in...
What am I doing wrong here?
/**
* Log In (log a user into the application)
*
* #param Request $request
* #return Response
*/
public function login(Request $request)
{
// update the last login at time
try {
$user = User::findOrFail(Auth::id());
$user->last_login_at = Carbon::now()->toDateTimeString();
$this->resetExpiryAlerts($user, Auth::id());
$user->save();
} catch (\Exception $e) { }
// success
return $this->respondWithToken($token);
}
/**
* Reset expiry alerts
*
*/
public function resetExpiryAlerts($user, $id)
{
$domains = Domains::where('user_id', $id)
->where('domain_last_notified_at', '!=', null)
->orWhere('ssl_last_notified_at', '!=', null)
->get();
if (count($domains) > 0) {
foreach ($domains as $key => $domain) {
if (
isset($domain->domain_last_notified_at) &&
($user->last_login_at >= $domain->domain_last_notified_at)
) {
$domain->domain_last_notified_at = null;
}
if (
isset($domain->ssl_last_notified_at) &&
($user->last_login_at >= $domain->ssl_last_notified_at)
) {
$domain->ssl_last_notified_at = null;
}
$domain->save();
}
}
}
I've removed some irrelevant code from my example, but I think I'm doing something wrong with the query...
$domains = Domains::where('user_id', $id)
->where('domain_last_notified_at', '!=', null)
->orWhere('ssl_last_notified_at', '!=', null)
->get();
Because it appears to be returning any domain regardless of the user ID.
I think the problem is in your query. The last two wheres should be grouped. Try the following:
Domains::where('user_id', $id)
->where(function ($query) {
$query->whereNotNull('domain_last_notified_at')
->orWhereNotNull('ssl_last_notified_at');
})
->get();

Difference between dates always returns a default number(5) in the database

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

Transfer variable from one to another function in controller

I am using Laravel at this time to secure a page when a user enters their password on a modal form before it opens. I initialized a variable named $crypt, which is hidden in the form, to make every page unique (to prevent other people from opening the page with a URL).
I want to pass the $crypt data to the PDFView. How can I do that? I've tried a lot of things but none worked.
Error
Undefined variable: crypts
Route:
Route::get('/pdfview/{id}/', 'HomeController#pdfview')->name('pdfview');
Generated key code
<div style="display: none">{{ $crypt = str_random(10)}}
Controller
public function encryptslip(Request $request, $crypt)
{
$crypts = $crypt;
$id = $request->nip;
$pass = $request->password;
$nip = Auth::user()->nip;
if (Hash::check($pass, Auth::user()->password)) {
return redirect('/pdfview/' . $nip . '/', ['crypts' => $crypts])->with('crypt', $crypt);
} else {
return redirect('/home')->with('alert', 'Incorrect password');
}
}
public function pdfview(Request $request, $id)
{
$route = url()->current();
$month = Carbon::now()->month;
$periodeinput = DB::table('payrollinput')->where('nip', '=', $id)->orderBy('periode', 'desc')->pluck('periode')->implode('periode');
$periodehistory = DB::table('payrollhistory')->where('nip', '=', $id)->orderBy('periode', 'desc')->pluck('periode')->implode('periode');
// if ($periodeinput !== $month && $periodehistory !== $month) {
// return redirect('home')->with('alert', 'Slip gaji anda siap.');
// } else {
if (Auth::user()->nip == $id) {
$employees = MasterEmployee::where('nip', '=', $id)->first();
$payrollhistory = MasterPayrollHistory::where('nip', '=', $id)->where('periode', '=', $month)->first();
$payrollinput = MasterPayrollInput::where('nip', '=', $id)->where('periode', '=', $month)->first();
view()->share('employees', $employees);
view()->share('payrollhistory', $payrollhistory);
view()->share('payrollinput', $payrollinput);
view()->share('id', $id);
// calculation code
return view('pdfview', ['id' => $id])->with('id', $id)
->with('earningtotal', $earningtotal)
->with('deductiontotal', $deductiontotal)
->with('takehomepay', $takehomepay)
->with('total', $total);
} else {
return redirect('home')->with('alert', 'Sorry it is personally confidential, you are not able to see it.');
}
}
View
<div><{{$crypts}}</div>
when you use return redirect() method that variable is passed to the view as a session variable and in the blade it must be called form
<div>{{session('crypts')}}</div>
to convert this session variable on $request
{{Form:hidden('crypts', json_encode(session('crypts'))}}

capture user id when login and save user id based on operations

I need to capture login user and when i add question i need to save the corresponding user id in the questions table.i'm getting user id when i login but it is not saving in the question table
Controller with store function
public function store(Request $request)
{
//
$last_que = Question::orderBy('question_id', 'desc')->first();
if ($last_que != null) {
$old_queId = $last_que->question_id;
$old_queId = $old_queId + 1;
} else {
$old_queId = 1;
}
$qorder=$request->input('order');
$question=new Question();
$quest=$question->checkDuo($qorder);
if(count($quest)==0)
{
$que=Question::create([
'question'=>$request->input('question'),
'question_id'=>$old_queId,
'question_type'=>$request->input('qtype'),
'question_schedul'=>$request->input('qschedule'),
'created_user_id'=>Session::get('created_id'),
'order_no'=>$request->input('order')
]);
if($que)
{
return redirect()->route('questions.index')->with('success', 'Successfully saved');
}
}
else
{
return redirect()->back()->with('fail', 'Unable to save..! Entry with same order no. already exist');
}
}
in Login index file this is i used capture the user id
<?php
if (!empty($id)) {
Session::put('created_id', $id);
}
?>
Login controller
public function postSignIn(Request $request)
{
if (Auth::attempt(['username' => $request['username'], 'password' => $request['password']])) {
$user = DB::table('users')->where([['username', '=', $request['username']], ['status', '=', '0']])->first();
$user_id = $user->user_id;
return redirect()->route('dashboard', $user_id)->with('message', 'State saved correctly!!!');
} else {
return redirect()->back();
}
}
Get user ID. use something like this.
Auth:user()->id;
Or you can use
Session::getId();
Change this line,
'created_user_id'=>Session::get('created_id'),
To,
'created_user_id'=>Auth::id(),
You used $user_id
return redirect()->route('dashboard', $user_id)->with('message', 'State saved correctly!!!');
Than asking:
if (!empty($id)) {
This $id will be always empty so use:
<?php
if (!empty($user_id)) {
Session::put('created_id', $user_id);
}
?>

How to restrict withdrawal in laravel?

When user sign up he get free amount of 100, amount is present in the "USERS" table. I want that a user cannot withdraw (amount in "Withdraw" table), if he has no record in the "Fund" table.
I tried the following in the withdraw controller. If the "Fund" table holds a record, it will return the view, otherwise it will redirect to login.
Is this right?
public function newWithdraw()
{
$fund = Fund::where('user_id', Auth::user()->id)->first();
if ($fund==null)
{
Session::flash('type','danger');
Session::flash('message','please add funds atleast once');
return redirect()->route('login');
}
else
$data['general'] = GeneralSetting::first();
$data['site_title'] = $data['general']->title;
$data['basic'] = BasicSetting::first();
$data['page_title'] = "User Withdraw Method";
$data['method'] = ManualPayment::whereStatus(1)->get();
return view('withdraw.withdraw-new',$data);
}
Use empty() to check Fund have a record or not.
public function noamount()
{
$fund = Fund::where('user_id', Auth::user()->id)->first();
if (empty($fund)) {
return redirect()->back()->with('type','danger')->with('message','please add funds atleast once');
}
}

Categories