Testing a variable against 3 tables in Laravel - php

i am having a hard time getting this code block to work:
public function verifyPayment(Request $request)
{
$transaksie = Transaksie::where('trans_nommer', $request->trans_nommer)->firstOrFail();
$transaksie->is_paid = 4;
$transaksie->save();
// Notify user that transaction was successfull
$transaksie->user->notify(new PaymentVerified($transaksie));
// Merk die sertifikaat as verkoop
if($request->sert_nommer >= 1003333) {
$sertifikaat = Alternate::where('sert_nommer', $request->sert_nommer)->firstOrFail();
$sertifikaat->is_paid = 4;
$sertifikaat->save();
}elseif($request->sert_nommer <= 1003604) {
$sertifikaat = Share::where('sert_nommer', $request->sert_nommer)->firstOrFail();
$sertifikaat->is_paid = 4;
$sertifikaat->save();
}elseif($request->sert_nommer <= 50000) {
$sertifikaat = Aandeel::where('sert_nommer', $request->sert_nommer)->firstOrFail();
$sertifikaat->is_paid = 4;
$sertifikaat->save();
}
// Notify seller that transaction was approved
$sertifikaat->user->notify(new BetalingSuccess($sertifikaat));
$sertifikate = Alternate::orderBy('id','DESC')->first();
$old_sert = $sertifikate->sert_nommer;
$aandeel_sert = $old_sert + 1;
$transaksie->user->alternates()->create([
'sert_nommer' => $aandeel_sert,
'user_id' => $transaksie->user->lid_nommer,
'aantal_aandele' => $transaksie->aandele,
'nfc_bedrag' => $transaksie->nfc,
'status_id' => 3,
'is_paid' => 2,
]);
$alt_sertifikate = Alternate::orderBy('id', 'DESC')->first();
$tweede_sertifikaat = $alt_sertifikate->sert_nommer;
$nfc_sert = $tweede_sertifikaat + 1;
$transaksie->user->alternates()->create([
'sert_nommer' => $nfc_sert,
'user_id' => $transaksie->user->lid_nommer,
'aantal_aandele' => $transaksie->aandele,
'nfc_bedrag' => $transaksie->nfc,
'status_id' => 3,
'is_paid' => 2,
]);
// Notify user van nuwe sertifikaate en stuur mail deur queue
$user = $transaksie->user;
dispatch(new StuurSertifikate($aandeel_sert,$nfc_sert,$transaksie,$user))->onQueue('emails');
return redirect()->back()->with('success','Betaling was geverifieer!');
}
What i am trying to achieve is that the $request->sert_nommer must check if it is in the Alternates table, Share table or the Aandeel table. All this code works on my local server with no errors but when I test this on my production server I get a 404 when it reaches this part of the query

Change your query a little bit and it should work (not tested):
if($request->sert_nommer >= 1003333) {
$sertifikaat = Alternate::where('sert_nommer', $request->sert_nommer)->first();
if($sertifikaat){
$sertifikaat->is_paid = 4;
$sertifikaat->save();
}
}elseif($request->sert_nommer <= 1003604) {
$sertifikaat = Share::where('sert_nommer', $request->sert_nommer)->first();
if($sertifikaat){
$sertifikaat->is_paid = 4;
$sertifikaat->save();
}
}elseif($request->sert_nommer <= 50000) {
$sertifikaat = Aandeel::where('sert_nommer', $request->sert_nommer)->first();
if($sertifikaat){
$sertifikaat->is_paid = 4;
$sertifikaat->save();
}
}
The findOrFail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown. If the exception is not caught, a 404 HTTP response is automatically sent back to the user.
For more details see official doc

Related

im trying to make a query on laravel but it's returning this error message

I'm trying to get all item series from a deposit but the deposit id is on a related table. On this function i'll list all the series between two sequences requested
public function getSeries($params = [])
{
$data = collect($params);
$inicio = $data->only('serie_in');
$fim = $data->only('serie_fi');
$depOrigem = $data->only('id_origem');
$series = [];
for($i = $inicio; $i <= $fim; ++$i)
{
$item = Item::leftJoin('produtoItem', 'produtoItem.id', '=', 'item.id_produtoItem')->where('serie', $i)->where('produtoItem.id_deposito', $depOrigem)->first();
if(empty($item))
{
$status = 'I';
}
else
{
$status = $item->status;
}
$series[] = [
'serie' => $i,
'status' => $status
];
}
$result = [
'status' => true,
'data' => $series
];
return $result;
}
This is the error message, i'm thinking that must be as sintax error, but a dont realy know what? Can you help me?
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 2031 (SQL: select * from item left join produtoItem on produtoItem.id = item.id_produtoItem where serie = ? limit 1) in file /usr/share/nginx/html/controleestoque/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 671
I was calling the request on my controller without a validator, so i rewrite the getSeries method.
public function getSeries(Request $request){
$data = $request->only(['serie_in', 'serie_fi', 'id_origem']);
$result = $this->produto_service->getSeries($data);
return response()->json($result);
}
And my function work it !

MariabDB synchronous UPDATE query

I'm working with PHP and MariaDB and I run into a problem.
I update a value to multiple rows, and then SELECT there rows to make a new calculation the data for another task.
The problem here that I get the wrong number. I guess that the MariaDB has not finished the UPDATE query, but it return the finished flag to PHP and then the PHP proceeds the SELECT query. [I just guess]
I open to any idea. If I'm wrong, please correct me.
Thank you for sharing
This is my code
$modelAdminOrderBidSys = $this->load->model('Admin\Order\BidSys');
$acceptedItem = typeCast($modelAdminOrderBidSys->getItem($cartItemId));
if (!$acceptedItem) {
return array(
'result' => 'error',
'message' => 'Cannot find item #' . $cartItemId
);
}
$acceptedItem['lastOffer'] = $acceptedItem['offer'];
$acceptedItem['accepted'] = 1;
$acceptedItem['isBot'] = 0;
$modelAdminOrderBidSys->updateItem($cartItemId, array2object($acceptedItem));
$cartItems = typeCast($modelAdminOrderBidSys->getItems($acceptedItem['cartId']));
$accepted = 1;
$total = 0;
$offer = 0;
$lastOffer = 0;
foreach($cartItems as $cartItem) {
if ((int)$cartItem['accepted'] < 1) {
$accepted = 0;
}
$total += (float)$cartItem['total'];
$offer += (float)$cartItem['offer'];
$lastOffer += (float)$cartItem['lastOffer'];
}
$postField = new \stdClass();
$postField->accepted = $accepted;
$postField->total = $total;
$postField->offer = $offer;
$postField->lastOffer = $lastOffer;
$modelAdminOrderBidSys->updateCart($acceptedItem['cartId'], $postField);
It sounds like your SELECT transaction starts before the UPDATE has committed. Try changing the transaction_isolation (in config) / tx_isolation (at runtime with SET GLOBAL) to READ-COMMITTED. Default is REPEATABLE-READ.

Getting "Integrity constraint violation (Duplicate entry for key)" in Laravel

I have a table that I have recently edited to add another index using two columns (which combined are required to be unique).
The problem is now I get an error when I go to create a new model record:
Integrity constraint violation: 1062 Duplicate entry ... for key ....
The two columns are titled:
shipment_origin
pro_number
So as an example, the end result would look like: 1-230185
And I have checked, the record is created technically, it just doesn't follow through and the error is returned. So to make it simple, there is no record before hand (so there's no duplicate entry), a record is created in the database and the error is returned (no matter what).
Or is there a way to go about doing this directly through Laravel rather than MySQL?
Update
Here is the public function in my controller:
public function store(Request $request)
{
$this->validate(request(), [
'pro_number' => 'required',
'shipment_origin' => 'required'
/*'piecesNumber' => 'required' (had to remove for now, but must review)*/
]);
$user_id = Auth::id();
$input = $request->all();
//Save Initial Shipment Data
$shipment = new Shipment();
$shipment->pro_number = request('pro_number');
$shipment->shipment_origin = request('shipment_origin');
$shipment->date = request('date');
$shipment->due_date = request('due_date');
$shipment->tractor_id = request('tractor_id');
$shipment->trailer_id = request('trailer_id');
$shipment->driver_id = request('driver_id');
$shipment->notes = request('notes');
$shipment->shipper_no = request('shipper_no');
$shipment->ship_to = request('ship_to');
$shipment->ship_from = request('ship_from');
$shipment->bill_to = request('bill_to');
$shipment->bill_type = request('bill_type');
$shipment->load_date = request('load_date');
$shipment->shipment_status = 1;
$shipment->shipment_billing_status = (isset($request->shipment_billing_status) && !empty($request->shipment_billing_status)) ? $request->shipment_billing_status : 1;
$shipment->created_by = $user_id;
$shipment->cn_billtoName = request('cn_billtoName');
$shipment->cn_billtoAddress1 = request('cn_billtoAddress1');
$shipment->cn_billtoAddress2 = request('cn_billtoAddress2');
$shipment->cn_billtoCity = request('cn_billtoCity');
$shipment->cn_billtoState = request('cn_billtoState');
$shipment->cn_billtoZip = request('cn_billtoZip');
$shipment->cn_billtoEmail = request('cn_billtoEmail');
$shipment->cn_billtoPhone = request('cn_billtoPhone');
$shipment->cn_shiptoName = request('cn_shiptoName');
$shipment->cn_shiptoAddress1 = request('cn_shiptoAddress1');
$shipment->cn_shiptoAddress2 = request('cn_shiptoAddress2');
$shipment->cn_shiptoCity = request('cn_shiptoCity');
$shipment->cn_shiptoState = request('cn_shiptoState');
$shipment->cn_shiptoZip = request('cn_shiptoZip');
$shipment->cn_shiptoEmail = request('cn_shiptoEmail');
$shipment->cn_shiptoPhone = request('cn_shiptoPhone');
$shipment->cn_shipfromName = request('cn_shipfromName');
$shipment->cn_shipfromAddress1 = request('cn_shipfromAddress1');
$shipment->cn_shipfromAddress2 = request('cn_shipfromAddress2');
$shipment->cn_shipfromCity = request('cn_shipfromCity');
$shipment->cn_shipfromState = request('cn_shipfromState');
$shipment->cn_shipfromZip = request('cn_shipfromZip');
$shipment->cn_shipfromEmail = request('cn_shipfromEmail');
$shipment->cn_shipfromPhone = request('cn_shipfromPhone');
$shipment->fuelChargeDesc = request('fuelChargeDesc');
$shipment->fuelChargeAmt = request('fuelChargeAmt');
$shipment->fuelChargeTotal = request('fuelChargeTotal');
$shipment->permitChargeDesc = request('permitChargeDesc');
$shipment->permitChargeAmt = request('permitChargeAmt');
$shipment->permitChargeTotal = request('permitChargeTotal');
$shipment->otherChargeDesc = request('otherChargeDesc');
$shipment->otherChargeAmt = request('otherChargeAmt');
$shipment->otherChargeTotal = request('otherChargeTotal');
$shipment->noCharge = request('noCharge');
$shipment->noSettle = request('noSettle');
$shipment->Total = request('Total');
if ((request('shipment_billing_status') == 2) || (request('shipment_billing_status') == 3)){
$balance = 0.00;
}else{
$balance = request('Total');
}
$shipment->Balance = $balance;
$shipment->freightBillSubtotal = request('freightBillSubtotal');
$shipment->save();
//Save Shipment Details
for ($i = 0; $i < count($request->shipment_details['piecesNumber']); $i++) {
//the first line used to be 'shipment_id' => $shipment->pro_number,
Shipment_Detail::create([
'shipmentID' => $shipment->id,
'pieces_number' => $request->shipment_details['piecesNumber'][$i],
'pieces_type' => $request->shipment_details['piecesType'][$i],
'rate_type' => $request->shipment_details['rateType'][$i],
'charge' => $request->shipment_details['charge'][$i],
'weight' => $request->shipment_details['weight'][$i],
'hazmat' => $request->shipment_details['hazmat'][$i],
'description' => $request->shipment_details['description'][$i] ]);
}
$carrier = \App\Customer::where('carrier','=',1)->get();
foreach($carrier as $car){
$carrierUsers = $car->users;
if ($carrierUsers->count() > 0){
foreach($carrierUsers as $carrierUser){
$carrierUser->notify(new FreightBillNew($shipment));
}
}
}
Session::flash('success_message','Freight Bill Successfully Created'); //<--FLASH MESSAGE
//Return to Register//
return redirect('/shipments/accounts');
}

save all associated records at once

I am able to save associated records in cakephp3 but if you look at the code , the records are not saved all at once with 1 save call.
I did have a problem trying to save all the records at once. If you look at how its done you see the Guardian and Users table are save separately.
The code works and saves the records but saving all at once in 1 save call has been an issue as I got an error on the guardian table.
Guardians have a 1 to many relationship with students
Students and Users have a 1 to 1
Students to subjects and availabilityFotStudents both have a many to many
Code
public function add($gId=0) {
$this->loadModel("Guardians");
$this->loadModel('PaymentTypes');
$this->set("title","Add Student");
$guardians=null;
if ($gId>0){
$guardians =$this->Guardians->get($gId);
}
if ($this->request->is('post')) {
if ( $this->request->data['studenttype']==0){ //enquiry
$this->request->data['students']['address_billing'] = 0;
$this->request->data['students']['student_enq'] = 1;
}
else if ( $this->request->data['studenttype']==1){ //waitlist
$this->request->data['students']['address_billing'] = 1;
$this->request->data['students']['student_enq'] = 0;
}
else if ( $this->request->data['studenttype']==2){ //skip waitlist
$this->request->data['students']['address_billing'] = 4;
$this->request->data['students']['student_enq'] = 0;
}
if ( $this->request->data['students']['tutoring_typest_id']==1){
$this->request->data['students']['group_status']=0;
}
else if ( $this->request->data['students']['tutoring_typest_id']>1){
$this->request->data['students']['group_status']=1;
}
if ($this->request->data['students']['tutoring_typest_id']==3 ){//group only
$this->request->data['students']['address_billing'] = 4;
}
$data = $this->request->data;
// debug($data);
$uname= $this->request->data['Users']['username'];
if ($this->Students->Users->findByUsername($uname)->count()) {
$this->Flash->error(__('Username exists. Please, try again.'));
return $this->redirect(["action"=>"add",$gId]);
}
$userId=0;
$entity = $this->Students->Users->newEntity($this->request->data['Users'],['validate'=>false]);
$entity->role = "student";
$entity['role_id'] = 4;
$entity = $this->Students->Users->save($entity);
// debug( $entity);
$studentUserId = $entity->id;
if($guardians==null) {
$guardians = $this->Guardians->newEntity($this->request->data['guardians'], ['validate' => false]);
}
$guardianEntity = $this->Guardians->save($guardians);
$guardians = $this->Students->newEntity();
$studentData = $this->request->data['students'];
$studentData['subjects'] = $this->request->data['subjects'];
$studentData['availability_for_students'] = $this->request->data['availability_for_students'];
$studentEntity = $this->Students->patchEntity($guardians,$studentData,
[
"validate"=>false,
'associated' => [
"AvailabilityForStudents"=>["validate"=>false],
"Subjects"=>["validate"=>false]
]
]
);
$studentEntity->guardian_id = $guardianEntity->id;
$studentEntity->user_id = $studentUserId;
$studentEntity = $this->Students->save($studentEntity,
[
"validate"=>false,
'associated' => [
"AvailabilityForStudents"=>["validate"=>false],
"Subjects"=>["validate"=>false]
]
]
);
if ($studentEntity) {
$this->Flash->success(__('The student has been saved'));
return $this->redirect(["action"=>"index2"]);
} else {
$this->Flash->error(__('The student could not be saved. Please, try again.'),'flash_alert');
}
}//post
$subjects = $this->Students->Subjects->find('list', array( 'order' => array('Subjects.name' => 'asc') ));
$weekdays = $this->Students->weekDays;
$tutoringTypes = $this->Students->TutoringTypeStudents->find('list');
//$payments = $this->Student->paymentOptions;
$this->PaymentTypes->primaryKey("name");
$payments = $this->PaymentTypes->find( 'list', array(
'fields' => array('PaymentTypes.name','PaymentTypes.name')) );
$referrals = $this->Students->Referrals->find('list');
$tutorGender = $this->Students->Lessons->Tutors->tutorGender;
$this->set('guardians', $guardians);
$this->set(compact('referrals','subjects', 'tutoringTypes', 'weekdays','payments','tutorGender'));
}
you can use Tranactional data save. Where you can run multiple save method. if any save method failed then no data will be save. so it works like "1 save call" which you mentioned

No 'Access-Control-Allow-Origin' header even thou other requests from the same domain are working

I have a strange error, with No 'Access-Control-Allow-Origin' header. I understand that I have to give some permission the origin domain(client) to be able to access the server and that works fine with some other requests I make. But when it comes to one other function to call, it says No 'Access-Control-Allow-Origin' header only.
I have my client hosted in heroku and server in godaddy...
This is the function when that error shows:
public function store(Request $request)
{
$ffSpending = new FriendsFamilySpending();
$ffSpending->user_id = Auth::user()->id;
$ffSpending->team_id = Auth::user()->student->team_id;
$ffSpending->management_units = $request->input('management_units');
$ffSpending->sales_units = $request->input('sales_units');
$ffSpending->product_units = $request->input('product_units');
$ffSpending->ip_units = $request->input('ip_units');
$ffSpendingRules = array(
'management_units' => 'required',
'sales_units' => 'required',
'product_units' => 'required',
'ip_units' => 'required'
);
$ffSpendingValidator = \Validator::make($ffSpending->getAttributes(), $ffSpendingRules);
if ($ffSpendingValidator->passes()) {
$team = Team::find($ffSpending->team_id);
$currentBalance = $this->teamService->checkBalance($team);
//Baseline costs
$BASELINE = FriendsFamilySpending::BASELINE;
//Get Prices for each unit
$IP_ONE_TIME_COST = OperationalExpensePrice::getPrice(OperationalExpense::IP, $request->input('ip_units'), OperationalExpenseSerie::FF);//one-time IP costs
$MANAGEMENT = OperationalExpensePrice::getPrice(OperationalExpense::MANAGEMENT, $request->input('management_units'), OperationalExpenseSerie::FF);
$SALES = OperationalExpensePrice::getPrice(OperationalExpense::SALES, $request->input('sales_units'), OperationalExpenseSerie::FF);
$PRODUCT = OperationalExpensePrice::getPrice(OperationalExpense::PRODUCT, $request->input('product_units'), OperationalExpenseSerie::FF);
//Monthly Costs
$quartlyCosts = $BASELINE + $MANAGEMENT + $SALES + $PRODUCT;
$newBalance = $currentBalance;
$workingMoney = $newBalance - $IP_ONE_TIME_COST;
$minimumMonth = 12; // the minimum amount of time they must be able to afford (Staging Day = 12 months)
//Calculate how many months they (team) can survive
$survivingMonths = 0;
while ($workingMoney >= $quartlyCosts) {
$workingMoney = $workingMoney - $quartlyCosts; //deduct monthly costs from the current working money
$survivingMonths = $survivingMonths + 3; // quartly spending
if ($survivingMonths > 24) { // team survives the whole staging and deal day
break;
}
}
// month to minute - Conversation ratio
$monthToMinute = 6.25; // (75min / 12month) = 6.25min a month
$totalMinutes = $survivingMonths * $monthToMinute;
$minMinutes = 75; //the minimum amount of time they must be able to afford
//Check if team makes it till the deal day
if ($survivingMonths < $minimumMonth) {
return response()->json(['message' => 'With your current spending plan, you will not make it to deal day. Please try again with less spending plan. Currently you run out of money after ' . $totalMinutes . ' minutes. You have to survive at least 75 minutes."', 'success' => false, 'status' => 500, 'data' => null]);
}
$ffSpendingRes = $this->ffSpendingService->save($ffSpending);
if ($ffSpendingRes) {
$this->ffSpendingService->score(Auth::user()->student->team->class_id); // update ff spending scoring
$this->ffSpendingService->updateTotalScore(Auth::user()->student->team->class_id);
//Update balance
$team = Team::find($ffSpending->team_id);
$this->teamService->updateBalance($team, $workingMoney);
if ($survivingMonths >= $minimumMonth && $survivingMonths < 24) {
$survivingMonthsAfterStagingDay = $survivingMonths - $minimumMonth;
$survivingMonthsAfterStagingDayToMinute = $survivingMonthsAfterStagingDay * $monthToMinute;
$outOfMoney = new OutOfMoney();
$outOfMoney->team_id = Auth::user()->student->team_id;
$outOfMoney->stage = OutOfMoney::$FF_SPENDING;
$outOfMoney->is_running_out_of_money_on_deal_day = 1;
$outOfMoney->month = $survivingMonthsAfterStagingDay;
$outOfMoney->minutes = $survivingMonthsAfterStagingDayToMinute;
$outOfMoney->monthly_cost = $quartlyCosts;
$outOfMoney->save();
} else {
$outOfMoney = new OutOfMoney();
$outOfMoney->team_id = Auth::user()->student->team_id;
$outOfMoney->stage = OutOfMoney::$FF_SPENDING;
$outOfMoney->is_running_out_of_money_on_deal_day = 0;
$outOfMoney->monthly_cost = $quartlyCosts;
$outOfMoney->save();
}
return response()->json(['message' => 'Success', 'success' => true, 'status' => 200, 'data' => $ffSpending]);
} else {
return response()->json(['message' => 'Error', 'success' => false, 'status' => 500, 'data' => null]);
}
} else {
return response()->json(['message' => 'Validation Failed', 'success' => false, 'status' => 400, 'data' => array('class' => $ffSpendingRules)]);
}
Note: if I change the function and make it simple, like return 'test', it does not show anymore that origin access error.
I wonder if there is any problem with function, why does not it show the actuall error, but it show that cors error instead.
Any suggestion?
What's happening is an ORIGINS request is coming in and getting declined because it's not in your allowed methods.
'allowedMethods' => ['GET', 'POST', 'PUT', 'DELETE', 'ORIGINS']
You'll also want to set your allowedOrigins to something.
I always use MDN for reference.

Categories