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

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');
}

Related

php call a class function in loop multiple time issue

I have an issue with one of API, where this API will create Order information. Each Order represents 1 buyer with multiple items. I want to loop the items in my API method. But, when I try to loop the function, it only stores the first array value, which is not what I want. I want to store a whole array of values to the Database.
Here is the API Code:
$s = $data->ItemIDs;
if($order->CreateOrderInfo()){
echo 'Order created successfully.';
echo "---";
for($i = 0; $i < sizeof($s); $i++){
$order->ItemCode = $s[$i];
$order->GetItemInfo();
if ($order->ItemCode != null){
$item_array = array(
'UserMememberNo' => $order->UserMememberNo,
'Image' => $order->Image,
'Description' => $order->Description,
'Price' => $order->Price,
'ItemBrand' => $order->ItemBrand,
'ItemModel' => $order->ItemModel
);
//GET DATA FOR ITEM TABLE
$order->ItemGUID = $data->ItemGUID;
$order->ItemName = $order->Description;
$order->ItemPrice = $order->Price;
$order->ItemQuantity = $data->ItemQuantity;
$order->ItemVariation1 = $data->ItemVariation1;
$order->ItemVariation2 = $data->ItemVariation2;
$order->ItemVariation3 = $data->ItemVariation3;
$order->ItemVariation4 = $data->ItemVariation4;
$order->ItemVariation5 = $data->ItemVariation5;
}
else{
echo json_encode('No item Found');
}
if($order->CreateItemInfo())
{
echo 'Item created';
}else{
echo 'Unable to create item';
echo '----';
}
}
if($order->CreateBuyerInfo()){
echo 'Buyer information created';
}else{
echo 'Unable to create buyer information';
}
Here is the model. This model is for inserting the values into the Database:
//CREATE FUNCTION FOR ITEM TABLE
public function CreateItemInfo() {
$sqlQuery = "INSERT INTO ".$this->item_info_table."
SET
GUID = :GUID,
ItemGUID = :ItemGUID,
ItemName = :ItemName,
ItemPrice = :ItemPrice,
ItemQuantity = :ItemQuantity,
ItemVariation1 = :ItemVariation1,
ItemVariation2 = :ItemVariation2,
ItemVariation3 = :ItemVariation3,
ItemVariation4 = :ItemVariation4";
$stmt = $this->conn->prepare($sqlQuery);
$this->GUID = htmlspecialchars(strip_tags($this->GUID));
$this->ItemGUID = htmlspecialchars(strip_tags($this->ItemGUID));
$this->ItemName = htmlspecialchars(strip_tags($this->ItemName));
$this->ItemPrice = htmlspecialchars(strip_tags($this->ItemPrice));
$this->ItemQuantity = htmlspecialchars(strip_tags($this->ItemQuantity));
$this->ItemVariation1 = htmlspecialchars(strip_tags($this->ItemVariation1));
$this->ItemVariation2 = htmlspecialchars(strip_tags($this->ItemVariation2));
$this->ItemVariation3 = htmlspecialchars(strip_tags($this->ItemVariation3));
$this->ItemVariation4 = htmlspecialchars(strip_tags($this->ItemVariation4));
$stmt->bindParam(":GUID", $this->GUID);
$stmt->bindParam(":ItemGUID", $this->ItemGUID);
$stmt->bindParam(":ItemName", $this->ItemName);
$stmt->bindParam(":ItemPrice", $this->ItemPrice);
$stmt->bindParam(":ItemQuantity", $this->ItemQuantity);
$stmt->bindParam(":ItemVariation1", $this->ItemVariation1);
$stmt->bindParam(":ItemVariation2", $this->ItemVariation2);
$stmt->bindParam(":ItemVariation3", $this->ItemVariation3);
$stmt->bindParam(":ItemVariation4", $this->ItemVariation4);
if($stmt->execute()) {
return true;
}
return false;
}
A screenshot below shows the issue, where only the first value of the array is successfully inserted to the Database.
Result of Database Insert

Shorter way in php laravel to load a model in another similar one?

I want to copy every property of the contract model into this another templatecontract model and so on. My code works, but I don't know much about laravel (or php in fact) and my intuition tells me that there must be a better way, or more elegant way.
fill() from Laravel does not get much better. Maybe with a constructor?
Equal tables:
Contract -> TemplateContract
Chapter -> TemplateChapter
Clause -> TemplateClause
public function storeTemplate(ContractCreateRequest $request)
{
DB::beginTransaction();
try
{
$contract = Contract::find($request->input()['type']);
$templatecontract = new TemplateContract();
$templatecontract->id = $contract->id;
$templatecontract->pid = $contract->pid;
$templatecontract->deleted = $contract->deleted;
$templatecontract->sorting = $contract->sorting;
$templatecontract->created_at = $contract->created_at;
$templatecontract->updated_at = $contract->updated_at;
$templatecontract->deleted_at = $contract->deleted_at;
$templatecontract->title = $contract->title;
$templatecontract->description = $contract->description;
$templatecontract->hidden = $contract->hidden;
$templatecontract->contract_type = $contract->contract_type;
$templatecontract->process_type = $contract->process_type;
$templatecontract->tstamp = $contract->tstamp;
$templatecontract->is_english = $contract->is_english;
$templatecontract->usecasetitle = $contract->usecasetitle;
if (Auth::user()) {
$templatecontract->user_id = Auth::user()->id;
}
if($templatecontract->save())
{
$chapter = DB::table('chapter')->where('contract', $templatecontract->id)->get();
if(isset($chapter))
{
foreach ($chapter as $key => $value) {
$templatechapter = new TemplateChapter();
$templatechapter->clause = $value->clause;
$templatechapter->contract = $value->contract;
$templatechapter->created_at = $value->created_at;
$templatechapter->deleted = $value->deleted;
$templatechapter->headlinetype = $value->headlinetype;
$templatechapter->hidden = $value->hidden;
$templatechapter->id = $value->id;
$templatechapter->must = $value->must;
$templatechapter->note = $value->note;
$templatechapter->sorting = $value->sorting;
$templatechapter->title = $value->title;
$templatechapter->tstamp = $value->tstamp;
$templatechapter->updated_at = $value->updated_at;
$templatechapters[] = $templatechapter;
if($templatechapter->save())
{
$clause = DB::table('clause')->where('chapter', $value->id)->get();
if(isset($clause))
{
foreach ($clause as $key => $value) {
$templateclause = new TemplateClause();
$templateclause->id = $value->id;
$templateclause->chapter = $value->chapter;
$templateclause->clausetext = $value->clausetext;
$templateclause->variable = $value->variable;
$templateclause->topic = $value->topic;
$templateclause->deleted = $value->deleted;
$templateclause->selectword = $value->selectword;
$templateclause->shortinfo = $value->shortinfo;
$templateclause->sorting = $value->sorting;
$templateclause->created_at = $value->created_at;
$templateclause->updated_at = $value->updated_at;
$templateclause->hidden = $value->hidden;
$templateclause->tstamp = $value->tstamp;
$templateclause->save();
$templateclauses[] = $templateclause;
}
}
}
}
}
}
//DB::commit();
return response()->success(__('success.showing', ['resource' => 'des Vertrags', 'resourceE' => 'contract']), $templatecontract, 200);
}
catch (Exception $e)
{
return response()->error(__('error.showing', ['resource' => 'des Vertrags', 'resourceE' => 'contract']), 400, $e);
}
}
So almost all of the props from the request matches with the column names. You just need to call the create method of Eloquent model to create a new record and pass key value pair but rather an object. Also, you need not to worry about the extra parameters $contract contains since Laravel will only extract and assign params defined in protected $fillable property of the class.
// cast object to array
$contract = (array) $contract;
$templateContract = TemplateContract::create($contract)

Laravel 5.4 - Update an existing record

I'm struggling to update an existing record through an Eloquent Model in Laravel 5.4
I have for creating a record that works perfectly fine, I took it and modified it to try and update the record:
public function commitEdit ($char_edit_id)
{
$edited_character = \DB::table('characters')->where('char_id', $char_edit_id)->first();
$edited_character->campaign_id = 1;
$edited_character->character_name = request('characterName');
$edited_character->Race = request('race');
$edited_character->Sub_Race = request('subRaceField');
$edited_character->Class = request('class');
$edited_character->Level = request('level');
$edited_character->Strength = request('strength');
$edited_character->Dexterity = request('dexterity');
$edited_character->Constitution = request('constitution');
$edited_character->Intelligence = request('intelligence');
$edited_character->Wisdom = request('wisdom');
$edited_character->Charisma = request('charisma');
$levelVar = request('level');
if ($levelVar >= 4) {
$edited_character->Proficiency = 2;
} else if ($levelVar >= 8) {
$edited_character->Proficiency = 3;
}
$edited_character->Trained_Skills = request('skillsField');
$edited_character->Languages = request('languagesField');
$edited_character->Hit_Die = 1;
$edited_character->max_HP = request('max-hp');
$edited_character->Alignment = request('alignment');
$edited_character->Armor_Class = request('armor-class');
$edited_character->Initiative = request('initiative');
$edited_character->Speed = request('speed');
$edited_character->Background = request('background');
$edited_character->update();
return redirect('./characters');
That gives this error:
Call to undefined method stdClass::update()
I have tried using save() but I get the same error with save() instead of update()
Thanks in advance c:
Documentation
If you just need to retrieve a single row from the database table, you may use the first method. This method will return a single StdClass object:
$edited_character is a stdClass, no Eloquent model.
You can try this code:
public function commitEdit ($char_edit_id)
{
$edited_character = \DB::table('characters')->where('char_id', $char_edit_id)->update([
'campaign_id' => 1,
'character_name' => request('characterName'),
'Race' => request('race'),
//others property
]);
}
Or create Characters model which will be extends from Illuminate\Database\Eloquent\Model and use save method:
public function commitEdit ($char_edit_id)
{
$edited_character = Characters::where('char_id', $char_edit_id)-first();
//your code with properties
$edited_character->save();
}
You can try this way:
public function commitEdit ($char_edit_id)
{
$edited_character = Characters::find($char_edit_id);
$edited_character->character_name = request('characterName');
$edited_character->Race = request('race');
$edited_character->Sub_Race = request('subRaceField');
$edited_character->Class = request('class');
$edited_character->Level = request('level');
$edited_character->Strength = request('strength');
$edited_character->Dexterity = request('dexterity');
$edited_character->Constitution = request('constitution');
$edited_character->Intelligence = request('intelligence');
$edited_character->Wisdom = request('wisdom');
$edited_character->Charisma = request('charisma');
$levelVar = request('level');
if ($levelVar >= 4) {
$edited_character->Proficiency = 2;
} else if ($levelVar >= 8) {
$edited_character->Proficiency = 3;
}
$edited_character->Trained_Skills = request('skillsField');
$edited_character->Languages = request('languagesField');
$edited_character->Hit_Die = 1;
$edited_character->max_HP = request('max-hp');
$edited_character->Alignment = request('alignment');
$edited_character->Armor_Class = request('armor-class');
$edited_character->Initiative = request('initiative');
$edited_character->Speed = request('speed');
$edited_character->Background = request('background');
if($edited_character->save()){
return redirect('./characters');
}else{
// show error message
}
}

Auto increment Invoice ID in Code-igniter

i am very new to code igniter /php .
Before i was using randomly generated invoice number like
$invoice_no = rand(9999,9999999999);
But now i wanted to increment invoice number and add current year as a prefix to it . But somewhere i am doing wrong as this code failed execute . Can some one point me in the right direction .
My model is ...
function insertInvoice($data)
{
$this->db->trans_begin();
$invoice = array();
if(!empty($data['client_id']))
{
$invoice['invoice_client_id'] = $data['client_id'];
}else{
$client_data = array(
'client_name' => $data['customername'],
'client_address1' => $data['address1']
);
$this->db->insert('client_details', $client_data);
$insert_id = $this->db->insert_id();
$invoice['invoice_client_id'] = $insert_id;
}
$query = $this->db->query("SELECT * FROM invoice ORDER BY invoice_id DESC LIMIT 1");
$result = $query->result_array(0);
$result ++;
$curYear = date('Y');
$invoice_no = $curYear . '-' .$result;
$invoice['invoice_no'] = $invoice_no;
$invoice['invoice_subtotal'] = $data['subTotal'];
$invoice['invoice_tax'] = $data['tax'];
$invoice['invoice_tax_amount'] = $data['taxAmount'];
$invoice['invoice_total'] = $data['totalAftertax'];
$invoice['invoice_total_extra'] = $data['totalextra'];
$invoice['invoice_rent'] = $data['rent'];
$invoice['invoice_paid'] = $data['amountPaid'];
$invoice['invoice_due'] = $data['amountDue'];
$invoice['invoice_desc'] = $data['notes'];
$invoice['invoice_items_count'] = $data['item_count'];
$invoice['invoice_extra_count'] = $data['extra_count'];
$invoice['invoice_miscellaneous'] = $data['miscellaneous'];
$this->db->insert('invoice', $invoice);
$i=1;
do {
$items = array(
'invoice_no' => $invoice_no,
'item_name' => $data['invoice']['product_name'][$i],
'item_price' => $data['invoice']['product_price'][$i],
'item_qty' => $data['invoice']['product_qty'][$i],
'item_total' => $data['invoice']['total'][$i],
'item_noof_crate_wait' => $data['invoice']['noof_crate_wait'][$i],
'item_crate_wait' => $data['invoice']['crate_wait'][$i],
'item_choot' => $data['invoice']['choot'][$i],
'item_net_quantity' => $data['invoice']['net_qty'][$i]
);
$this->db->insert('invoice_items',$items);
$i++;
} while($i<$data['item_count']);
$j=1;
do {
$extraitems = array(
'invoice_no' => $invoice_no,
'extra_item_name' => $data['extra']['name'][$j],
'extra_item_qunatity' => $data['extra']['qty'][$j],
'extra_item_price' => $data['extra']['price'][$j],
'extra_item_total' => $data['extra']['total'][$j]
);
$this->db->insert('extra_items',$extraitems);
$j++;
} while($j<$data['extra_count']);
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
return FALSE;
}
else
{
$this->db->trans_commit();
return TRUE;
}
}
invoice_id is primary key in DB .
You're attempting to increment the result array but what you really need is to acquire and increment a field value.
//you only need one field so ask only for that
$query = $this->db->query("SELECT invoice_id FROM invoice ORDER BY invoice_id DESC LIMIT 1");
//you really should check to make sure $query is set
// before trying to get a value from it.
//You can add that yourself
//Asked for only one row, so only retrieve one row -> and its contents
$result = $query->row()->invoice_id;
$result ++;
...
I'm guessing you're getting an "Object conversion to String error" on line $invoice_no = $curYear . '-' .$result;
Since $result contains an object and you're using it as a string. Print the $result variable to check how to use the data assigned to it.

Cannot use object of type Entity\X as array

I have little problem, I have no idea what's wrong with my code :/
$ilosc = $_POST["ilosc"];
$recipe = new Recipe();
$em = $this->getDoctrine()->getManager();
$repository = $this->getDoctrine()->getRepository('MainBundle:Recipe');
$query = $repository->createQueryBuilder('p')->select('p.id')->where('p.nazwa = :nazwa AND p.adres = :adres')->setParameters(array('nazwa' => $_POST["nazwaprzepisu"], 'adres' => $_POST["adresprzepisu"]))->getQuery();
$test = $query->getResult();
$id = $test[0]['id'];
$idprod = $_POST['idprod'];
$iloscprod = $_POST['iloscprod'];
for ($i = 0; $i < $ilosc; $i++)
{
$ingredient = new Ingredient();
$repositorying = $this->getDoctrine()->getRepository('MainBundle:Ingredient');
$query = $repositorying->createQueryBuilder('p')->select('p')->where('p.przepis_id = :id AND p.produkt_id = :idprod')->setParameters(array('id' => $id, 'idprod' => $idprod[$i]))->getQuery();
$result = $query->getResult();
if(!$result)
{
$ingredient->setProduktId($idprod[$i]);
$ingredient->setPrzepisId($id);
$ingredient->setIlosc($iloscprod[$i]);
}
else
{
$nowailosc = $result[0]['ilosc'] + $iloscprod[$i];
$stareid = $result[0]['id'];
echo "kokoko";
}
$em->persist($ingredient);
$em->flush();
}
I have problem with those two lines:
$nowailosc = $result[0]['ilosc'] + $iloscprod[$i];
$stareid = $result[0]['id'];
I get an error:
"Fatal error: Cannot use object of type My\MainBundle\Entity\Ingredient as array in".
Somebody have idea what I am doing wrong?
Problem solved. I had to use:
$nowailosc = $result[0]->getIlosc() + $iloscprod[$i];
$stareid = $result[0]->getId();

Categories