How to update a row from a different row data using laravel - laravel

By clicking verify button I want the status of payment to change from pending to verified, then the pending amount (in payments table) to sum up with the wallet balance amount in users table and the final balance updated in users table using Laravel. This is my controller. Please help
public function verify_payment($user_id,$payment_data,$id){
$wallet = Mpesa::findOrFail($id);
$wallet->status = 'verified';
if($wallet->save()){
flash(__('Payment has been approved successfully'))->success();
return redirect()->route('all.payments');
}
$top_up = User::findOrFail($user_id);
$top_up->amount = $payment_data['amount'];
$top_up->balance = $top_up->balance + $payment_data['amount'];
$top_up->save();
flash(__('Something went wrong'))->error();
return back();
}

public function verify_payment($user_id,$payment_data,$id){
$wallet = Mpesa::findOrFail($id);
$wallet->status = 'verified';
if($wallet->save()){
flash(__('Payment has been approved successfully'))->success();
}
$top_up = User::findOrFail($user_id);
$top_up->amount = $payment_data['amount'];
$top_up->balance = $top_up->balance + $payment_data['amount'];
$top_up->save();
flash(__('Something went wrong'))->error();
return redirect()->route('all.payments');
}

Related

Laravel model is updating multiple models instead of single

I am trying to update my model using multiple where conditions.
my code is
public function UpdateEducationData(Request $request)
{
$user = app('user');
// return $request;
$education = eduinfo::where("id", $user->id)->where("exam", $request->type)->first();
// dump sql query for debugging
// $education->rawSql();
// dd($education);
$education->board = $request->board;
// $education->degree = $request->degree;
$education->year = $request->year;
$education->rollno = $request->rollno;
$education->obtainmarks = $request->obtainmarks;
$education->totalmarks = $request->totalmarks;
$education->division = $request->division;
$education->grade = $request->grade;
$education->totalcgpa = $request->totalcgpa;
$education->obtailcgpa = $request->obtailcgpa;
// update education based on exam
$education->save();
return redirect()->back()->with("message", "Education Information Updated Successfully");
return "Update Education Data";
}
My code is updating a eduinfo table based on id and exam. But whenever this function is called it updates all eduinfo records related to that user id.
I tried to update eduinfo table single record but multiple records are being update at once. I dumped eduinfo after retriving the model and yes it's retrieving the single model using first() method but still when save() is called it updates all records of that user id in eduinfo.
I think Your conditions to make a unique record are not.
But if you wanna Just run one time! I have an offer to you.
$flag=true;
if($flag){
$user = \Auth::user();
$education = eduinfo::where('id','=', $user->id)->where('exam','=', $request->type)->first();
$education->board = $request->board;
$education->year = $request->year;
$education->rollno = $request->rollno;
$education->obtainmarks = $request->obtainmarks;
$education->totalmarks = $request->totalmarks;
$education->division = $request->division;
$education->grade = $request->grade;
$education->totalcgpa = $request->totalcgpa;
$education->obtailcgpa = $request->obtailcgpa;
$education->save();
$flag=false;
}
It's depends on my answer.

Code Issue when clicks "Return to Merchant" Button of Paypal

I am using Codeigniter to integrate the PayPal payment gateway on my website.
//This is my buy method
public function buy($id){
$course = $this->course_model->fetch_course_details_for_buy($id);
$returnURL = base_url().'paypal/success'; //payment success url
$cancelURL = base_url().'paypal/cancel'; //payment cancel url
$notifyURL = base_url().'paypal/ipn'; //ipn url
$userID = $this->session->userdata('student_id'); //current user id
$_SESSION['course_id'] = $course->course_id;
$logo = base_url().'assets/images/test-logo.png';
$this->paypal_lib->add_field('return', $returnURL);
$this->paypal_lib->add_field('cancel_return', $cancelURL);
$this->paypal_lib->add_field('notify_url', $notifyURL);
$this->paypal_lib->add_field('item_name', $course->title);
$this->paypal_lib->add_field('custom', $userID);
$this->paypal_lib->add_field('item_number', $course->course_id);
$this->paypal_lib->add_field('amount', $course->amount);
$this->paypal_lib->image($logo);
$this->paypal_lib->paypal_auto_form();
}
This is my PayPal's class method of success
function success(){
//get the transaction data
$paypalInfo = $this->input->get();
$data['item_number'] = $paypalInfo['item_number'];
$data['txn_id'] = $paypalInfo["tx"];
$data['payment_amt'] = $paypalInfo["amt"];
$data['currency_code'] = $paypalInfo["cc"];
$data['status'] = $paypalInfo["st"];
//pass the transaction data to view
$this->load->view('paypal/success', $data);
}
This is my IPN method
function ipn(){
//paypal return transaction details array
$paypalInfo = $this->input->post();
$data['user_id'] = $paypalInfo['custom'];
$data['product_id'] = $paypalInfo["item_number"];
$data['txn_id'] = $paypalInfo["txn_id"];
$data['payment_gross'] = $paypalInfo["mc_gross"];
$data['currency_code'] = $paypalInfo["mc_currency"];
$data['payer_email'] = $paypalInfo["payer_email"];
$data['payment_status'] = $paypalInfo["payment_status"];
$paypalURL = $this->paypal_lib->paypal_url;
$result = $this->paypal_lib->curlPost($paypalURL,$paypalInfo);
//check whether the payment is verified
if(preg_match("/VERIFIED/i",$result)){
//insert the transaction data into the database
$this->product->insertTransaction($data);
}
}
My payment is successful done from the sandbox account. But When I click the return to merchant button after payment it's throwing error of undefined indexes as mention in the success method. I apply first a time payment gateway and don't know what is missing in my code. Any help is appreciable.
You should log what $paypalInfo contains.
If you have enabled PDT, information may be coming as a POST rather than a GET.
In any case, make your code be able to check for and handle the missing data/indices or put it in a try/catch equivalent; it should not error.

Save the total sum in my table (codeigniter)

Newbie at codeigniter here. how can I save my total amount in my table per user? The only thing I did is to sum it and show it on my view. My target is to save the total commission on my "agent_commission" table". I have provided a screenshot of my target for better visualization. Thank you in advance. Any help will be appreciated.
Views:
<?php $formattedNum = number_format($commCurrentBalance, 2);
echo $formattedNum;
?
Controller:
public function commi()
{
$data['activeNav'] = "";
$data['subnav'] = "commissions";
$this->header($data);
$this->nav();
$data['currentPoints']=$this->session->userdata('currentPoints');
$data['result'] = $this->commissions->get1();
$data['commCurrentBalance']=$this->load->commissions->gettotalcommi(); //getting sum of amount
$this->load->view('comm_view', $data);
$this->footer();
}
Model:
function gettotalcommi(){
$reqcommi= $this->session->userdata('uid');
$this->db->select_sum('amount');
$this->db->where('commTo',$reqcommi);
$result = $this->db->get('agent_commission_history')->row();
return $result->amount;
}
I'm not sure if it will work but please try
$db->select_sum('amount');
$db->where('commTo',$param);
$aq = $db->get_compiled_select('agent_commission_history');
$db->set('commCurrentBalance',"($aq)",false);
$db->where('commTo',$param2);
$db->update('agent_commission');
This is the Codeigniter equivalent of the query I posted earlier:
UPDATE agent_commission
SET commCurrentBalance = ( SELECT SUM(amount) FROM agent_commission_history WHERE commTo = ?)
WHERE commTo = ?
public function commi(){
$data['commCurrentBalance']=$this->load->commissions->gettotalcommi(); //getting sum of amount
$dataArray = array(
'commCurrentBalance'=>$data['commCurrentBalance']
);
$this->db->insert('agent_commission',$dataArray);
$this->load->view('comm_view', $data);
$this->footer();
}

Laravel generate password and insert user in database by hand

I have few users with no email and password, and I would like to update users by adding email from freemail column, and setup password from random string.
This is my sample code:
public function updateUserProfil()
{
//find list user to be update(juste one to test)
$users = User::where('isfree', '1')->first();
//Random string generate
$motdepasse = str_random(6);
//find user
$updateUser= User::find($users->id);
//setup fields
$updateUser->email = $users->freemail;
$updateUser->remember_token = str_random(10);
$updateUser->motdepasse = $motdepasse;
$updateUser->password = bcrypt($motdepasse);
$updateUser->isfree = 0;
$updateUser->save();
}
The problem is that when I try to connect with email($users->freemail) and password($motdepasse), which is not encrypted random string, I get error that:
my credential is not valid
what did I miss ?
You can use update() to update rows. So your code must be
public function updateUserProfil()
{
//find list user to be update(juste one to test)
$users = User::where('isfree', '1')->first();
//Random string generate
$motdepasse = str_random(6);
//find user
$updateUser= User::find($users->id);
//setup fields
$updateUser->update([
'email'=>$users->freemail,
'remember_token'=>str_random(10),
'motdepasse'=>$motdepasse,
'password'=>bcrypt($motdepasse),
'isfree'=>0,
]);
}

Updating and event start/end time Google Calendar, v3 api

I am using the Google API PHP client with Google Calendar.
I am having now problems creating the event, but when I try to update the datetime start/end the call just fails and the event is not updated.
I have successfully updated just the summary, but have been unable to update the start/end times.
private function _update_google_event($eventId = '', $updateData = array())
{
if(strlen($eventId) == 0 || empty($updateData)) return false;
$calendar = $this->_get_gcal();
//First get the event
$event = $calendar->events->get($this->calendar_id, $eventId);
var_dump($event->getId());
if(isset($updateData['summary'])) {
$event->setSummary($updateData['summary']);
}
if(isset($updateData['location'])) {
$event->setLocation($updateData['location']);
}
var_dump($event->getEnd());
/*
if(isset($updateData['start'])) {
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime($updateData['start']);
$event->setStart($start);
}
*/
if(isset($updateData['end'])) {
var_dump(new Google_EventDateTime());
$end = new Google_Service_Calendar_EventDateTime();
var_dump($end->setDateTime($updateData['end']));
$end->setDateTime($updateData['end']);
var_dump($event->setEnd($end));
}
//Update Sequence
$event->setSequence($event->getSequence() + 1);
echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n";
//var_dump($event);
//Send the update request
//$updatedEvent = new Google_Service_Calendar_Event($calendar->events->update($this->calendar_id, $event->getId(), $event));
$updatedEvent = $calendar->events->update($this->calendar_id, $event->getId(), $event);
echo $updatedEvent->getUpdated();
return false;
}
I have seen some stack overflow questions on updating events that mentioned needing to update the sequence number, so I have done so, but it does not change anything for start/end time.
Any tips/pointers would be much appreciated.
If any other details can help, please just ask.
Thank you!
I realized my problem was not in the function, but in the data that I'm passing itself.
$updateData['start'] and $updateData['end'] was being passed as a DateTime object. I resolved it by using DateTime::format and then passing it into the function.

Resources