03.12.2015 Views

laravel4cookbook

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

E-Commerce 273<br />

1 public function addAction()<br />

2 {<br />

3 $validator = Validator::make(Input::all(), [<br />

4 "account" => "required|exists:account,id",<br />

5 "items" => "required"<br />

6 ]);<br />

7<br />

8 if ($validator->passes())<br />

9 {<br />

10 $order = Order::create([<br />

11 "account_id" => Input::get("account")<br />

12 ]);<br />

13<br />

14 try<br />

15 {<br />

16 $items = json_decode(Input::get("items"));<br />

17 }<br />

18 catch (Exception $e)<br />

19 {<br />

20 return Response::json([<br />

21 "status" => "error",<br />

22 "errors" => [<br />

23 "items" => [<br />

24 "Invalid items format."<br />

25 ]<br />

26 ]<br />

27 ]);<br />

28 }<br />

29<br />

30 $total = 0;<br />

31<br />

32 foreach ($items as $item)<br />

33 {<br />

34 $orderItem = OrderItem::create([<br />

35 "order_id" => $order->id,<br />

36 "product_id" => $item->product_id,<br />

37 "quantity" => $item->quantity<br />

38 ]);<br />

39<br />

40 $product = $orderItem->product;<br />

41<br />

42 $orderItem->price = $product->price;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!