public function makeOrder(Request $request) { $validator = $this->validator($request->all()); if (!isset(\Auth::user()->name)) { if ($validator->fails()) { return redirect('order/save')->withErrors($validator)->withInput(); } } $input = $request->all(); $cartCollection = Cart::getContent(); $products = $cartCollection->toArray(); $productId = array_keys($products); if (isset(\Auth::user()->name)) { $authUser = \Auth::user(); $orderSave = Order::create(['telephone' => $authUser->telephone, 'user_name' => $authUser->name, 'email' => $authUser->email, 'adress' => $authUser->adress, 'town' => $authUser->town, 'comment' => $input['comment']]); } else { $orderSave = Order::create(['telephone' => $input['telephone'], 'user_name' => $input['name'], 'email' => $input['email'], 'adress' => $input['adress'], 'town' => $input['town'], 'comment' => $input['comment']]); } $order = Order::find($orderSave->id); $order->product()->attach($productId); foreach ($productId as $rm) { Cart::remove($rm); } return redirect(LaravelLocalization::setLocale() . "/")->with('msg', 'Направихте успешна поръчка. Ще се свържем скоро.'); }
public function store(OrderRequest $request) { $order = $request->all(); $order['user_id'] = Auth::id(); Order::create($order); return Redirect::to("/?timer=true"); }
/** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $input = $request->all(); Order::create($input); $request->session()->flash('flash_message', 'Order successfully added!'); return redirect()->back(); }
public function postOrder() { $member_id = \Auth::user()->id; $address = \Request::get('address'); $books_in_cart = \App\Cart::with('books')->where('member_id', '=', $member_id)->get(); $cart_total = \App\Cart::with('books')->where('member_id', '=', $member_id)->sum('total'); $order = \App\Order::create(['member_id' => $member_id, 'address' => $address, 'total' => $cart_total, 'created_at' => \Carbon\Carbon::now()]); $message = []; foreach ($books_in_cart as $cart_item) { // dobavlenie v pivot $order->orderItems()->attach($cart_item->book_id, ['amount' => $cart_item->amount, 'price' => $cart_item->books->price, 'total' => $cart_item->books->price * $cart_item->amount]); array_push($message, $cart_item); } // dd($books_in_cart[0]->books->title); // $to = '*****@*****.**'; // $subject = 'Tema'; // mail($to, $subject, implode($message)); // dd($message); \Mail::send('emails.order', ['cart' => $message, 'order' => $order], function ($msg) { // and a copy to users $msg->to(['*****@*****.**', \Auth::user()->email])->subject('Order'); }); //Udalyaem iz korziny vse Posle uspeshnogo dobavleniya v book_order //To est sozdaniya zakaza i dobavleniya ego v PIVOT \App\Cart::where('member_id', '=', $member_id)->delete(); return \Redirect::to('index')->with('message', 'Your order successfully added'); }
/** * agreed to buy * @param Request * @return [type] */ public function postBuy(Request $request) { //MENU $mainMenu = Category::getParentMenu(); $allMenu = Category::getAllMenu($mainMenu); //HOT PRODUCTS. $hotProduct = Product::hotProduct(); //DISCOUNT PRODUCTS. $discountProduct = Product::discountProduct(); if (\Session::has('giohang')) { $data = \Session::get('giohang'); if ($request->get('account_number') != null) { $account_number = $request->get('account_number'); } else { $account_number = null; } $transaction = ['customer_id' => \Auth::id(), 'ship_id' => \Session::get('ship'), 'pay_id' => \Session::get('pay'), 'amount' => \Session::get('total'), 'message' => $request->get('message'), 'security' => time(), 'account_number' => $request->get('account_number')]; //dd($transaction); $transactions = Transaction::create($transaction); //dd($transactions->toArray()); foreach ($data as $key => $value) { $order = ['transaction_id' => $transactions->id, 'product_id' => $value['id'], 'qty' => $value['qty'], 'price_order' => $value['price'], 'discount_order' => $value['discount']]; $orders = Order::create($order); } $this->getCancel(); return view('fornindex.shopping_succeed', compact('allMenu', 'hotProduct', 'discountProduct')); } }
/** * @param LoginCustomerFormRequest $request * @return \Illuminate\Http\RedirectResponse */ public function bagStore(LoginCustomerFormRequest $request) { /////////////////////// "AUTH" CLIENT /////////////////////// $customer_name = Input::get('customer_name'); $customer_email = Input::get('customer_email'); // si username + email (provenant des inputs) match avec ceux de la bdd : $customer = Customer::whereRaw('username = ? and email = ?', [$customer_name, $customer_email])->first(); if (!empty($customer)) { // on envois les datas en bdd : $order = Order::create($request->all()); // id du client : $customer_id = $customer->id; $order->customer_id = $customer_id; $order->save(); // On va associer LA commande aux produits en bdd : $paniers = Session::get("panier"); $newItems = []; foreach ($paniers as $panier) { $newItems[] = ['order_id' => $order->id, 'product_id' => $panier["product_id"], 'quantity' => $panier["quantity"]]; } DB::table('order_product')->insert($newItems); // on vide le panier : Session::forget('panier'); return redirect(url('/'))->with('message', 'Votre commande à bien été pris en compte !'); } else { return redirect()->back()->with('error', 'Erreur, nom d\'utilisateur ou mot de passe incorrect !'); } }
public function submitOrder(Request $request) { $this->validate($request, ['merchandiser_id' => 'required|integer', 'trade_no' => 'required|max:255', 'subject' => 'required|max:255', 'amount' => 'required|numeric', 'returnUrl' => 'required|url', 'notifyUrl' => 'required|url', 'items' => 'array']); $data = $request->all(); $merch = Merchandiser::where('status', 'alive')->findOrFail($data['merchandiser_id']); if ($this->verify($data, $merch['pubkey'])) { $order = Order::where('merchandiser_id', $merch['id'])->where('trade_no', $data['trade_no'])->first(); if (empty($order)) { if (parse_url($data['returnUrl'], PHP_URL_HOST) != $merch['domain'] || parse_url($data['notifyUrl'], PHP_URL_HOST) != $merch['domain']) { return $this->jsonFormat(null, 'Your URL must belongs to domain "' . $merch['domain'] . '"', '400'); } $order = Order::create(['merchandiser_id' => $data['merchandiser_id'], 'trade_no' => $data['trade_no'], 'subject' => $data['subject'], 'amount' => $data['amount'], 'items' => serialize($data['items']), 'returnUrl' => $data['returnUrl'], 'notifyUrl' => $data['notifyUrl']]); $order->items = unserialize($order->items); return $this->jsonFormat($order); } elseif ($order->status == 'pending') { $order->update(['subject' => $data['subject'], 'amount' => $data['amount'], 'items' => serialize($data['items'])]); $order->items = unserialize($order->items); return $this->jsonFormat($order); } else { return $this->jsonFormat(null, 'trade_no already exsits', '409'); } } else { return $this->jsonFormat(null, 'Signature Invalid or timestamp expired', '403'); } }
/** * Store a newly created resource in storage. * * @return Response */ public function store() { // $error = $this->validate($request, $this->rules, $this->messages); // if ($request->ajax() && $error == Null) { // return 'success'; // } $input = Input::all(); $input['city_id'] = 1; if (Auth::user()) { $input['client_id'] = Auth::user()->id; } if ($input['status_id'] == '') { $input['status_id'] = 1; } if ($input['payment_amount'] == '') { $input['payment_amount'] = 0; } // dd($input); $order = Order::create($input); foreach ($input['oe'] as $oe) { if ($oe['id'] < 0) { $oe['order_id'] = $order->id; $oe['status_id'] = 1; $oe['payment'] = 0; OrderEntry::create($oe); } } return Redirect::route('admin.orders.index')->with('message', 'Orders created'); }
public function getCustomerNewOrder(Request $request, Order $order, Payment $payment) { if ($request->ajax()) { $customer_id = $request->input('customer_id'); $order_amount = $request->input('amount') != '' ? $request->input('amount') : 0; $category = $request->input('category'); $balance = $payment->where('customer_id', $customer_id)->first(['account_balance']); if ($customer_id != '' && $order_amount != '') { if ($order_amount == 0) { return ['message' => 'Order Amount of (' . nairaFormater($order_amount) . ') is too small!', 'title' => 'Warning!', 'type' => 'warning']; } else { if ($balance->account_balance >= $order_amount) { $this->orders = $order->create(['order_amount' => $order_amount, 'order_category_id' => $category, 'customer_id' => $customer_id]); // Deduct order amount from balance $final_balance = $balance->account_balance - $order_amount; $payment->where('customer_id', $customer_id)->update(['account_balance' => $final_balance]); if ($this->orders->id) { $order->whereId($this->orders->id)->update(['receipt_number' => thcReceiptNoGenerator($this->orders->id)]); return ['message' => 'Your order of ' . nairaFormater($order_amount) . ' has been completed successfully!', 'title' => 'Order Complete!', 'type' => 'success', 'amount_balance' => $final_balance]; } else { return ['message' => 'An error occurred while completing your Order!', 'title' => 'Error!', 'type' => 'error']; } } else { return ['message' => 'Account Balance (' . nairaFormater($balance->account_balance) . ') is too low to complete your Order of ' . nairaFormater($order_amount) . '!', 'title' => 'Warning!', 'type' => 'warning']; } } } else { return ['message' => 'We can\'t seem to find your record!', 'title' => 'Error!', 'type' => 'error']; } } }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!$request->session()->has('order_id')) { $guest = new User(); $guest->is_guest = true; $guest->name = 'Gast'; if ($guest->save()) { $guestOrder = Order::create(['user_id' => $guest->id, 'status' => 0, 'city_id' => $request->session()->get('selectedCity')['id']]); $request->session()->put('user_id', $guest->id); $request->session()->put('order_id', $guestOrder->id); } else { abort(500); } } elseif (Auth::check()) { $databaseOrderID = Order::where('user_id', '=', Auth::id())->where('status', '=', 0)->first(); $sessionOrderID = $request->session()->get('order_id'); if (!count($databaseOrderID)) { $userOrder = Order::create(['user_id' => Auth::id(), 'status' => 0, 'city_id' => $request->session()->get('selectedCity')['id']]); $this->mergeOrders($userOrder->id, $sessionOrderID, $request); } $databaseOrderID = Order::where('user_id', '=', Auth::id())->first(); $sessionOrderID = $request->session()->get('order_id'); if ($databaseOrderID->id != $sessionOrderID) { $this->mergeOrders($databaseOrderID->id, $sessionOrderID, $request); } } return $next($request); }
public function run() { $faker = Faker::create(); //'ko_KR' foreach (range(1, 20) as $index) { Order::create(['product_name' => $faker->word, 'order_date' => $faker->dateTime, 'delivery_date' => $faker->dateTime, 'delivery_agency' => $faker->company, 'customer_name' => $faker->name, 'track_number' => $faker->randomNumber]); } }
public function run() { $faker = Faker::create(); $userIds = User::lists('id')->all(); foreach (range(1, 10) as $index) { Order::create(['user_id' => $faker->randomElement($userIds), 'location' => $faker->sentence(), 'delivered_at' => $faker->dateTime(), 'delivery_status' => $faker->numberBetween(0, 10)]); } }
/** * Обработчик запроса на заказ */ public function makeOrder(Request $request) { $this->validate($request, ['username' => 'required|max:255', 'company' => 'max:255', 'email' => 'required|email|max:255', 'phone' => 'required|max:255', 'product_title' => 'required']); // Сохранение в БД $order = Order::create(['username' => $request->username, 'company' => $request->company, 'email' => $request->email, 'phone' => $request->phone, 'comment' => $request->comment, 'product_title' => $request->product_title, 'status' => 1]); // Отправка на почту с помощью событий event(new OrderWasCreatedEvent($order)); return ['status' => 'ok']; }
/** * Run the database seeds. * * @return void */ public function run() { Order::create(['user_id' => 1, 'total_price' => 15, 'invoice_nr' => NULL]); Order::create(['user_id' => 2, 'total_price' => 40, 'invoice_nr' => 12345]); Order::create(['user_id' => 2, 'total_price' => 30, 'invoice_nr' => NULL]); Order::create(['user_id' => 2, 'total_price' => 1000, 'invoice_nr' => NULL]); Order::create(['user_id' => 3, 'total_price' => 50, 'invoice_nr' => 12345]); Order::create(['user_id' => 3, 'total_price' => 15, 'invoice_nr' => 666]); Order::create(['user_id' => 3, 'total_price' => 30, 'invoice_nr' => NULL]); }
public function run() { $faker = $this->getFaker(); $accounts = User::all(); foreach ($accounts as $account) { for ($i = 0; $i < rand(-1, 5); $i++) { Order::create(["user_id" => $account->id]); } } }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $user = Auth::user(); $selectedCity = $request->session()->get('selectedCity'); $order = $user->orders()->where('status_id', 1)->get(); if (!count($order)) { Order::create(['user_id' => $user->id, 'status_id' => 1, 'city_id' => $selectedCity['id']]); } return $next($request); }
/** * Run the database seeds. * * @return void */ public function run() { $statuses = OrderStatus::$statuses; $keys = array_keys($statuses); $faker = Factory::create(); $users = User::lists('id'); $addresses = Address::lists('id'); foreach (range(1, 30) as $index) { Order::create(['user_id' => $faker->randomElement($users), 'address_id' => $addresses[$index], 'status' => $faker->randomElement($keys), 'processed_on' => $faker->unixTime, 'shipped_on' => $faker->unixTime, 'expected_delivery_on' => $faker->unixTime, 'delivered_on' => $faker->unixTime]); } }
public function saveOpenOrder(Request $request) { $validator = Validator::make($request->all(), ['tanggal' => 'required|date', 'places' => 'required', 'karyawan_id' => 'required|exists:karyawans,id'], ['tanggal.required' => 'Tanggal tidak boleh kosong.', 'tanggal.date' => 'Input harus tanggal.', 'places.required' => 'Tempat tidak boleh kosong', 'karyawan_id.required' => 'Karyawan tidak boleh kosong.', 'karyawan_id.exists' => 'Karyawan tidak terdaftar.']); if ($validator->fails()) { return redirect()->back()->withErrors($validator)->withInput(); } $data_order_detail = $request->session()->has('data_order') ? $request->session()->get('data_order') : []; if (!count($data_order_detail)) { return redirect()->back()->withErrors(['no_details' => 'Tidak ada produk yang dipesan.'])->withInput(); } # Create Nota $setting = Setting::first(); // Get Last Order $tanggal = $request->get('tanggal'); $lastOrder = Order::where('tanggal', $tanggal)->get()->count(); $nota = $setting->init_kode . "-" . str_replace('-', '', date('dmY', strtotime($tanggal))) . ($lastOrder + 1); // Order $karyawan_id = $request->get('karyawan_id') ? $request->get('karyawan_id') : (Auth::check() ? Auth::user()->karyawan()->id : '1'); $order = $request->only(['tanggal']) + ['nota' => $nota, 'state' => 'On Going', 'karyawan_id' => $karyawan_id]; $order = Order::create($order); // Order Place $places = explode(',', $request->get('places')); $places = Place::whereIn('id', $places)->get(); $orderPlaces = []; foreach ($places as $place) { $placeType = $place->kategori_id; // For Redirect array_push($orderPlaces, ['order_id' => $order->id, 'place_id' => $place->id, 'harga' => $place->harga]); } OrderPlace::insert($orderPlaces); // Order Detail & Order Detail Bahan $produks = Produk::with(['detail' => function ($query) { $query->join('bahans', 'produk_details.bahan_id', '=', 'bahans.id'); }])->whereIn('id', array_keys($data_order_detail))->get(); $orderDetailBahan = []; foreach ($produks as $produk) { $id = $produk->id; // Order Detail $orderDetail = ['order_id' => $order->id, 'produk_id' => $produk->id, 'hpp' => CountHpp($produk), 'harga_jual' => $data_order_detail[$id]['harga'], 'qty' => $data_order_detail[$id]['qty'], 'use_mark_up' => $produk->use_mark_up, 'mark_up' => $produk->mark_up, 'note' => $data_order_detail[$id]['note']]; //echo "<pre>", print_r($orderDetail), "</pre>"; $orderDetail = OrderDetail::create($orderDetail); if ($produk->detail->count()) { // Order Detail Bahan foreach ($produk->detail as $pd) { array_push($orderDetailBahan, ['order_detail_id' => $orderDetail->id, 'bahan_id' => $pd->bahan_id, 'harga' => $pd->harga, 'qty' => $pd->qty, 'satuan' => $pd->satuan]); } } } OrderDetailBahan::insert($orderDetailBahan); $request->session()->forget('data_order'); Artisan::call('bahan:count'); Artisan::call('produk:count'); return redirect('/order?tgl=' . $tanggal . '&type=' . $placeType)->with('succcess', 'Sukses simpan data order.'); }
/** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @param $user_id * @return \Illuminate\Http\Response */ public function store(Request $request, $user_id) { $user = Auth::user(); if ($user->id != $user_id) { return $this->respondInsufficientPermissions('User not authorized for this request.'); } $request['user_id'] = $user->id; $request['location'] = $user->location; if (count($user->orders) != 0) { return $this->respondForbiddenRequest("User already has an open order"); } $order = Order::create($request->all()); return $this->respondCreated($this->orderTransformer->transform($order)); }
/** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\Response */ public function store(Request $request) { $qtys = $request->get('qty'); $charge = Cart::where('user_id', Auth::user()->id)->get()->map(function ($c) { return $c->product; })->sum(function ($p) use($qtys) { return $p->price * $qtys[$p->id]; }); $order = Order::create(['user_id' => Auth::user()->id, 'note' => $request->get('note'), 'charge' => $charge, 'status' => 'Cooking', 'address' => $request->get('address')]); foreach ($qtys as $pid => $qty) { OrderItem::create(['product_id' => $pid, 'order_id' => $order->id, 'qty' => $qty]); } Cart::where('user_id', Auth::user()->id)->delete(); return redirect('/')->with('success', 'Your order will be delivered to ' . $request->get('address') . ' soon.'); }
public function run() { $faker = Faker::create(); $users = User::get(); $products = Product::get(); for ($i = 0; $i < 10; $i++) { $user = $users->random(1); $status = $faker->randomElement(['open', 'paid', 'pending', 'installed', 'cancelled']); $order = Order::create(['user_id' => $user->id, 'status' => $status, 'end_date' => $status == 'installed' || $status == 'cancelled' ? $faker->dateTime() : null]); $random = $faker->numberBetween(1, 2); for ($y = 0; $y < $random; $y++) { $product = $products->random(1); OrderDetail::create(['order_id' => $order->id, 'product_id' => $product->id, 'price' => $product->price, 'quantity' => 1]); } } }
public function storeOrderGuest() { $order_guest = Session::get('order_guest'); $input = Request::all(); $order_guest['address'] = $input['address']; // $order_guest['email'] = $input['email']; $order_guest['phone'] = $input['phone']; $order = Order::create($order_guest); $oe['name'] = $input['name']; $oe['order_id'] = $order->id; $oe['status_id'] = 1; $oe['amount'] = 0; $oe['payment'] = 0; OrderEntry::create($oe); return redirect('/'); }
public function createOrder(CreateOrderRequest $request) { $order = \DB::transaction(function () use($request) { $order = Order::create($request->all()); $order->reference = \Hashids::encode($order->id); $order->save(); foreach (\Cart::content() as $item) { $order->addItem($item); } return $order; }); if ($order) { return response()->json(['success' => true, 'reference' => $order->reference], 200); } return response()->json(['success' => false]); }
/** * Run the database seeds. * * @return void */ public function run() { $users = User::all(); $faker = Faker\Factory::create(); foreach ($users as $user) { for ($i = 0; $i < rand(-1, 5); $i++) { $attachment = $faker->imageUrl($width = 640, $height = 480); $shipmentfee = $faker->randomFloat(2, 5, 100); $tax = $shipmentfee * 0.1; $subtotal = $faker->randomFloat(2, 5, 100); $total = $shipmentfee + $tax + $subtotal; $comment = $faker->paragraph(); Order::create(["user_id" => $user->id, "attachment" => $attachment, "status" => 'unpaid', "method" => 'pickup', "sub_total" => $subtotal, "tax" => $tax, "shipment_fee" => $shipmentfee, "total" => $total, "comment" => $comment]); } } }
public function store(Request $request) { //dd(Session::all()); //dd($request->all()); //$agent = new Agent(); //dd($agent->is('Windows')); //dd($request->getClientIp()); $this->validate($request, ['name' => 'required|string|max:50', 'company' => 'string|max:70', 'email' => 'required|email|max:70', 'phone' => 'required|numeric', 'services' => 'required', 'respond' => 'required', 'is_client' => 'in:0,1']); $input = $request->all(); $input['services'] = implode(',', $input['services']); $order = Order::create(['name' => $input['name'], 'company' => $input['company'], 'email' => $input['email'], 'phone' => $input['phone'], 'fax' => $input['fax'], 'description' => $input['description'], 'services' => $input['services'], 'respond' => $input['respond'], 'is_client' => $input['is_client'], 'hear_about' => $input['hear_about'], 'ip' => $request->getClientIp()]); Event::fire(new OrderFormSent($order)); Flash::success(trans('language.orderFormSubmitted')); //dd(Session::all()); return redirect()->back(); //return redirect(route('home')); }
public function success(Request $request) { // Find the vendor. Store the info in orders table. // TODO: send email. $products = Cart::content(); $buyer = Auth::user(); foreach ($products as $product) { $order = Order::create(['buyer_id' => $buyer->id, 'product_id' => $product->id, 'quantity' => $product->qty, 'subtotal' => $product->subtotal, 'status' => 'open']); } $vendor = User::find($request->vendor_id); Mail::send('emails.order', compact('products', 'vendor', 'buyer'), function ($m) use($buyer, $vendor) { $m->to($buyer->email, $buyer->name)->subject('Your Order for ' . $vendor->vendor_name . ' from ExpatVendors.com'); }); Cart::destroy(); // session()->flash('flash_message', 'Your order has been placed.'); // session()->flash('flash_message_important', true); return view('success', compact('products', 'vendor', 'buyer')); }
public function run() { Order::truncate(); Order::create(['service_id' => '5', 'status' => 'pending', 'user_id' => '5']); Order::create(['service_id' => '3', 'status' => 'onprogress', 'user_id' => '3']); Order::create(['service_id' => '2', 'status' => 'pending', 'user_id' => '2']); Order::create(['service_id' => '1', 'status' => 'failed', 'user_id' => '1']); Order::create(['service_id' => '4', 'status' => 'success', 'user_id' => '4']); }
public function createOrder(Request $request) { Log::info('OrderController.createOrder:'); $validator = Validator::make($request->all(), ['email' => 'required|email', 'address' => 'required', 'phone' => 'required|size:10', 'delivery_charges' => 'sometimes', 'payment_type' => 'sometimes|in:cod,online', 'items' => 'required']); if ($validator->fails()) { return response()->json(['response' => 'failure', 'message' => $validator->errors()]); } $order = Order::create($request->all()); $order_id = $order->id; $total_amount = 0; $msg = ""; if ($request->has('items')) { $input = $request->input('items'); foreach ($input as $i) { //Check whether the food item exists $food = Food::find($i['food_id']); if (!$food || $food->quantity < $i['ordered_quantity']) { $msg .= "Item " . $i['food_id'] . " is not available."; //return response()->json(['response' => 'failure', 'message' => $msg, 'order' => $order]); } else { //Add items to the order $i['order_id'] = $order_id; $order_detail = Order_detail::create($i); $total_amount += $food->price * $i['ordered_quantity']; //Update quantity in food table $food->quantity = $food->quantity - $i['ordered_quantity']; $food->save(); } } } if ($total_amount > 0) { $order->item_total = $total_amount; $order->status = 'placed'; $order->save(); Event::fire(new OrderPlaced($order)); Log::info('Order placed', ['id' => $order->id]); return response()->json(['response' => 'success', 'message' => $msg, 'order' => $order]); } else { //Delete the order record as none of the items are available $order->delete(); Log::info('Order Deleted as items are not available', ['id' => $order_id]); return response()->json(['response' => 'failure', 'message' => $msg]); } }
public function saveOrder($user, $cart) { $order = Order::create(['user_id' => $user->id]); $orderItems = []; foreach ($cart as $id => $item) { $orderItem = new OrderItem(); $orderItem->order_id = $order->id; $orderItem->product_id = $id; $orderItem->name = $item['name']; $orderItem->description = 'description'; $orderItem->price = $item['price']; $orderItem->quantity = $item['qty']; $orderItems[] = $orderItem; } $order->orderItems()->saveMany($orderItems); $order->total = $this->orderTotal($order->id); $order->save(); return $order; }
/** * Handle the event. * * @param OrderWasPlaced $event * @return void */ public function handle(OrderWasPlaced $event) { $amount = $event->amount; $country = $event->order['country']; $vatRate = 25; $billing_id = $event->billing_id; $customerName = $event->order['first_name'] . ' ' . $event->order['last_name']; $customerAddress = $event->order['street']; $customerCity = $event->order['city']; $customerZip = $event->order['zip']; $customerEmail = $event->order['email']; $customerPhone = $event->order['phone']; $sendSms = $event->order['sendSms']; $checkUser = Auth::check() ? Auth::user()->id : 1; $products = Cart::content(); // Specific for saving an invoice $date = Carbon::now()->format('Y-m-d'); $lines = []; foreach ($products as $product) { $lines[] = ['productId' => $product->options->billys_product_id, 'unitPrice' => $product->price / 100]; } $billy = new BillysBilling(env('BILLYS_KEY')); $billyContact = $billy->makeBillyRequest('POST', '/contacts', ['contact' => ['type' => 'person', 'organizationId' => env('BILLY_ORGANIZATION'), 'name' => $customerName, 'countryId' => $country, 'street' => $customerAddress, 'cityText' => $customerCity, 'zipcodeText' => $customerZip, 'phone' => $customerPhone, 'isCustomer' => true]]); $billyContactId = $billyContact->body->contacts[0]->id; $order = Order::create(['amount' => $amount, 'vat_rate' => $vatRate, 'stripe_billing_id' => $billing_id, 'customer_name' => $customerName, 'customer_address' => $customerAddress, 'customer_city' => $customerCity, 'customer_country' => $country, 'customer_zip' => $customerZip, 'customer_email' => $customerEmail, 'customer_phone_number' => $customerPhone, 'sendSms' => $sendSms, 'user_id' => $checkUser, 'billys_contact_id' => $billyContactId]); $billyInvoice = $billy->makeBillyRequest('POST', '/invoices', ['invoice' => ['organizationId' => env('BILLY_ORGANIZATION'), 'contactId' => $billyContactId, 'entryDate' => $date, 'paymentTermsDays' => 5, 'state' => 'approved', 'sentState' => 'unsent', 'invoiceNo' => $order->id, 'currencyId' => 'DKK', 'lines' => $lines]]); $order->billys_invoice_id = $billyInvoice->body->invoices[0]->id; $order->save(); }