I have Orders table, products table and OrderProduct table. In Orderproduct table I have quantity,total and subtotal columns, Every order has many products. The products price gets multiplied by the amount ordered and then stored inside a row called total in OrderProduct table and also the product gets multiplied with quantity to get Subtotal of each product and stored inside a row called Subtotal. The problem is how do I get subtotal and total of every order, (so every order should have total amount and also in every product should have Subtotal). Quantity works fine.
Here are my codes.
Order.php
class Order extends Model
{
public function products()
{
return $this->belongsToMany('App\Product')->withPivot('quantity','total','Subtotal');
}
}
Checkout Controller
public function store(Request $request)
{
//Insert into order product table
if ($order) {
foreach(session('cart') as $productId =>$item) {
if (empty($item)) {
continue;
}
$product = product::find($productId);
OrderProduct::create([
'order_id' => $order->id ?? null,
'product_id' => $productId,
'quantity' => $item['quantity'],
'total' =>$item['total'],
'Subtotal' =>$item['Subtotal'],
]);
}
return $order;
}
My Cart looks like this
public function addToCart($id)
{
$userId = Auth::id();
$products = Product::find($id);
if(!$products) {
abort(404);
}
$cart = session()->get('cart');
if(!$cart) {
$cart = [
$id => [
"name" => $products->name,
"quantity" => 1,
"price" => $products->price,
"image" => $products->image
]
];
session()->put('cart', $cart);
return redirect()->back()->with('success', 'Product added to cart successfully!');
}
if(isset($cart[$id])) {
$cart[$id]['quantity']++;
session()->put('cart', $cart);
return redirect()->back()->with('success', 'Product added to cart successfully!');
}
$cart[$id] = [
"pro_name" => $products->pro_name,
"quantity" => 1,
"pro_price" => $products->pro_price,
"image" => $products->image
];
session()->put('cart', $cart);
return redirect()->back()->with('success', 'Product added to cart successfully!');
}
And my loop
@foreach ($order->products as $product)
{
<td>$</td>
<td>$</td>
}
@endforeach
Any help will be appreciated.
from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2xalMIo
via IFTTT
Aucun commentaire:
Enregistrer un commentaire