Skip to content

Instantly share code, notes, and snippets.

@ilyalazarev31
Created February 18, 2026 05:51
Show Gist options
  • Select an option

  • Save ilyalazarev31/69f54cdf4fc9f63afa60a58f4f496d80 to your computer and use it in GitHub Desktop.

Select an option

Save ilyalazarev31/69f54cdf4fc9f63afa60a58f4f496d80 to your computer and use it in GitHub Desktop.
class OrderController extends Controller
{
public function store(Request $request)
{
$request->validate([
'user_id' => 'required|exists:users,id',
'items' => 'required|array',
'items.*.product_id' => 'required|exists:products,id',
'items.*.quantity' => 'required|integer|min:1'
]);
$total = 0;
foreach ($request->items as $item) {
$product = Product::find($item['product_id']);
$total += $product->price * $item['quantity'];
if ($product->stock < $item['quantity']) {
return back()->with('error', 'Not enough stock for ' . $product->name);
}
}
$order = Order::create([
'user_id' => $request->user_id,
'total' => $total,
'status' => 'pending'
]);
foreach ($request->items as $item) {
$order->items()->create([
'product_id' => $item['product_id'],
'quantity' => $item['quantity'],
'price' => Product::find($item['product_id'])->price
]);
Product::where('id', $item['product_id'])->decrement('stock', $item['quantity']);
}
Mail::to($order->user->email)->send(new OrderConfirmation($order));
return redirect()->route('orders.show', $order);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment