I have cart on my web store and so far everything works perfectly but I said when I try decrement the product quantity to product, the all product in my database will decrement Not just products in cart.
Here is my ordercontroller :
public function postOrder(Request $request) {
$validator = Validator::make($request->all(), [
'first_name' => 'required|max:30|min:2',
'last_name' => 'required|max:30|min:2',
'address' => 'required|max:50|min:4',
'address_2' => 'max:50|min:4',
'city' => 'required|max:50|min:3',
'state' => 'required|',
'zip' => 'required|max:11|min:4',
'full_name' => 'required|max:30|min:2',
]);
if ($validator->fails()) {
return redirect('/checkout')
->withErrors($validator)
->withInput();
}
$first_name = Input::get('first_name');
$last_name = Input::get('last_name');
$address = Input::get('address');
$address_2 = Input::get('address_2');
$city = Input::get('city');
$state = Input::get('state');
$zip = Input::get('zip');
$full_name = Input::get('full_name');
$user_id = Auth::user()->id;
$cart_products = Cart::with('products')->where('user_id', '=', $user_id)->get();
$cart_total = Cart::with('products')->where('user_id', '=', $user_id)->sum('total')
$charge_amount = number_format($cart_total, 2) * 100;
$order = Order::create (
array(
'user_id' => $user_id,
'first_name' => $first_name,
'last_name' => $last_name,
'address' => $address,
'address_2' => $address_2,
'city' => $city,
'state' => $state,
'zip' => $zip,
'total' => $cart_total,
'full_name' => $full_name,
));
foreach ($cart_products as $order_products) {
$order->orderItems()->attach($order_products->product_id, array(
'qty' => $order_products->qty,
'price' => $order_products->products->price,
'reduced_price' => $order_products->products->reduced_price,
'total' => $order_products->products->price * $order_products->qty,
'total_reduced' => $order_products->products->reduced_price * $order_products->qty,
));
}
// in the fact all product will decrement Not just products in cart
\DB::table('products')->decrement('product_qty', $order_products->qty);
Cart::where('user_id', '=', $user_id)->delete();
flash()->success('Success', 'Your order was processed successfully.');
return redirect()->route('cart');
}
I use program \DB::table('products')->decrement('product_qty', $order_products->qty);; for the decrement but in the fact all product will decrement Not just products in cart
The decrement you are using updates all records, as you have observed because you didn't constrain it to a specific record. You want to do this in your loop:
DB::table('products')
->where('id', '=', $order_products->product_id)
->decrement('product_qty', $order_products->qty);
Related
Hello i am trying to make a code that updates existing values by removing existing ones/add new ones or make changes in the existing values. This is the code i have done so far:
public function update(Request $request, $id)
{
$order = Order::find($id);
$request->validate([
'order_number' => 'required',
'client_id' => 'required',
'description' => 'required',
'productOrder' => 'required',
'productOrder.*.product_id' => 'required|distinct|exists:products,id',
'productOrder.*.amount' => 'required|numeric|min:1',
]);
$order->update($request->all());
foreach ($request->productOrder as $product) {
$values[] = [
'order_id' => $order->id,
'product_id' => $product['product_id'],
'amount' => $product['amount'],
];
$amount = Product::find($product['product_id']);
$totalValue = $product['amount'] + $amount->amount;
$amount->update(['amount' => $totalValue]);
// $order->products()->sync([$product['product_id'] => array(
// 'product_id' => $product['product_id'],
// 'amount' => $product['amount'], THIS CODE MAKES ERROR BY DELETING ALL THE VALUES EXCEPT ONE
// )]);
}
$order->products()->detach();
$order->products()->attach($values); //I WANT THE CODE TO DO THIS FUNCTIONS BASICALLY
$orders = Order::all();
$orders->load('client', 'products');
return view('orders/index', compact('orders'));
}
I think you should use this
$values = [];
foreach ($request->productOrder as $product) {
/* This is the sync id && This is the pivot column */
$values[$product['product_id']] = ['amount' => $product['amount']];
$amount = Product::find($product['product_id']);
$totalValue = $product['amount'] + $amount->amount;
$amount->update(['amount' => $totalValue]);
}
// $values keys must be a product_id and its value must be pivot values
$order->products()->sync($values);
Hello i have this code in Laravel that updates existing many-to-many relationship tables so when i use the sync command the values update wrong, this is the code:
public function update(Request $request, $id)
{
$order = Order::where('id', $id)->first();
$request->validate([
'order_number' => 'required',
'client_id' => 'required',
'description' => 'required',
'productOrder' => 'required',
'productOrder.*.product_id' => 'required|distinct|exists:products,id',
'productOrder.*.amount' => 'required|numeric|min:1',
]);
$order->update($request->all());
foreach ($request->productOrder as $product) {
$values[] = [
'order_id' => $order->id,
'product_id' => $product['product_id'],
'amount' => $product['amount'],
];
$amount = Product::find($product['product_id']);
$totalValue = $product['amount'] + $amount->amount;
$amount->update(['amount' => $totalValue]);
}
$order->products()->sync($values); //the problem is here
$orders = Order::all();
$orders->load('client', 'products');
return view('orders/index', compact('orders'));
}
If i have 2 values like:
Product1 -> amount: 250
Product2 -> 100
And i updatet these existing values to
Product1 -> amount: 350
Product2 -> 200
The result will be
Product2 -> 200
Product2 -> 200
If i make this line of code dd($order->products()->sync($values)); i get this result
If i add a new product with the existing ones i get this result
From what im understanding the first result is replaced with the second one or removed, why does this happen?
So, you have this code:
public function update(Request $request, $id)
{
$order = Order::where('id', $id)->first();
$request->validate([
'order_number' => 'required',
'client_id' => 'required',
'description' => 'required',
'productOrder' => 'required',
'productOrder.*.product_id' => 'required|distinct|exists:products,id',
'productOrder.*.amount' => 'required|numeric|min:1',
]);
$order->update($request->all());
foreach ($request->productOrder as $product) {
$values[] = [
'order_id' => $order->id,
'product_id' => $product['product_id'],
'amount' => $product['amount'],
];
$amount = Product::find($product['product_id']);
$totalValue = $product['amount'] + $amount->amount;
$amount->update(['amount' => $totalValue]);
}
$order->products()->sync($values); //the problem is here
$orders = Order::all();
$orders->load('client', 'products');
return view('orders/index', compact('orders'));
}
The issue with it, is that sync is getting wrong IDs, because $values has numeric autoincrementals IDs: 0, 1, 2, etc.
What you need to pass to the sync is either an array of IDs [1, 2, 3], or an array of arrays (when you want to update columns related to that ID, for example: [1 => ['amount' => 100], 2, 3].
Let me try to modify your code to help you.
Let's assume you orders table and products table. You also have a pivot table called order_product table, so you store the relation in there. This order_product table has:
id
order_id
product_id
amount
So, your code should be like this:
public function update(Request $request, $id)
{
$validated = $request->validate([
'order_number' => 'required',
'client_id' => 'required',
'description' => 'required',
'productOrder' => 'required',
'productOrder.*.product_id' => 'required|distinct|exists:products,id',
'productOrder.*.amount' => 'required|numeric|min:1',
]);
$order = Order::find($id); // I would change this to use implicit binding
$order->update($validated); // Don't use $request->all(), you are using unvalidated values
foreach ($request->productOrder as $product) {
$values[$product['product_id']] = [
'amount' => $product['amount']
];
$amount = Product::find($product['product_id']);
$totalValue = $product['amount'] + $amount->amount;
$amount->update(['amount' => $totalValue]);
}
$order->products()->sync($values); // Now it will work
$orders = Order::all();
$orders->load('client', 'products');
return view('orders/index', compact('orders'));
}
I am working with a purchase ordering app. I have two tables, the orders table, and order_items. I would like to order_items to grab the id of orders which is in a single action. apology if I wasn't able to explain it clearly. here's my store function.
public function store(Request $request) {
$orders = $request->only(
'user_id',
'status_id',
'currency_id',
'company_id',
'purchase_no',
'notes',
'delivery_date',
'publish'
);
$orders['grandtotal'] = (float) str_replace(',', '', $request->grandtotal);
$orders = Orders::create($orders);
$input = $request->all();
for($i=0; $i<= count($input['quantity']); $i++) {
if(empty($input['quantity'][$i]) || !is_numeric($input['quantity'][$i])) continue;
$items = [
'order_id' => $input['order_id'][$i],
'product_id' => $input['product_id'][$i],
'product_code' => $input['product_code'][$i],
'product_name' => $input['product_name'][$i],
'cost' => $input['cost'][$i],
'quantity' => intval($input['quantity'][$i]),
'total_cost' => (float) str_replace(',', '', $input['total_cost'][$i]),
];
Orderitems::create($items);
}
return redirect()->route('orders.index');
}
what should I do to achieve this process? thank you so much in advance!
Just replace $input['order_id'][$i] with $orders->id, It might help you.
$items = [
'order_id' => $orders->id,
'product_id' => $input['product_id'][$i],
'product_code' => $input['product_code'][$i],
'product_name' => $input['product_name'][$i],
'cost' => $input['cost'][$i],
'quantity' => intval($input['quantity'][$i]),
'total_cost' => (float) str_replace(',', '', $input['total_cost'][$i]),
];
Hi guys I want to add products in differents column in database, however all I have done it was inserting all products in same column. thanks
my code:
$products = $request->all();
foreach( $products as $product) {
$invoice->products([
'name' => $product['name'],
'price' => $product['price'],
'qty' => $product['qty'],
'total' => $product['total']
]);
}
results
database shot
sorry new here
$products = $request->all();
$name = $products['name'];
$price = $products['price'];
$qty = $products['qty'];
$total = $products['total'];
foreach( $name as $key => $n) {
$invoice->products()->create([
'invoice_id' => $invoice->id,
'name' => $name[$key],
'price' => $price[$key],
'qty' => $qty[$key],
'total' => $total[$key]
]);
}
I'm working on some e-commerce website based on merchant. There is problem comping in submitting order. the problem is when i'm selecting same merchant that time order will be stored successfully, but when i'm selecting multiple product from different merchant that time my function through error of Undefined offset:1. Here is my function.
public function post_order(){
$data = Input::all();
$count = count($data['invoice_no']);
$order = array();
for($i=0; $i<$count; $i++){
if(!empty($data['invoice_no'][$i])){
array_push($order, array(
'order_no' => $data['order_no'][$i],
'invoice_prefix' => $data['invoice_prefix'][$i],
'invoice_no' => $data['invoice_no'][$i],
'merchant_id' => $data['merchant_id'][$i],
'customer_id' => $data['customer_id'][$i],
'buytokri_order' => $data['order_name'][$i],
'name' => $data['name'][$i],
'pincode' => $data['pincode'][$i],
'address' => $data['address'][$i],
'landmark' => $data['landmark'][$i],
'city' => $data['city'][$i],
'state' => $data['state'][$i],
'country' => $data['country'][$i],
'mobile' => $data['mobile'][$i],
'subtotal' => $data['selling_price'][$i],
'payment_type' => $data['payment_type'][$i],
'txn_id' => $data['txn'][$i],
'shipping' => $data['shipping'][$i],
'total' => $data['subtotal'][$i]
));
}
}
Order::insert($order);
$var = $data['order_no'];
foreach ($var as $vars) {
$id = DB::table('ads_order')->where('order_no', $vars)->get();
}
$count = count($data['invoice_no']);
$orderhistory = array();
for($i=0; $i<=$count; $i++){
if(!empty($data['invoice_no'][$i])){
array_push($orderhistory, array(
'order_id' => $id[$i]->id,
'merchant_id' => $data['merchant_id'][$i],
'customer_id' => $data['customer_id'][$i],
'order_status' => $data['order_status'][$i],
'comment' => $data['comment'][$i],
'notify' => $data['notify'][$i],
'default' => $data['default'][$i],
'status' => $data['status'][$i]
));
}
}
Orderhistory::insert($orderhistory);
return Redirect::intended('/ordersuccess');
}