/** * * @return \Hypersistence\Core\DB */ public static function &getDBConnection() { if (!is_null(self::$conn) && self::$conn instanceof DB) { return self::$conn; } else { $conf = simplexml_load_file(__DIR__ . '/../dbconf.xml'); self::$conn = new DB("{$conf->dbms}:host={$conf->host};dbname={$conf->database};charset={$conf->charset}", $conf->username, $conf->password, array(self::ATTR_PERSISTENT => true, self::ATTR_STATEMENT_CLASS => array('\\Hypersistence\\Core\\Statement'), self::ATTR_PERSISTENT => false)); if (!self::$conn->inTransaction()) { self::$conn->beginTransaction(); } return self::$conn; } }
public function postRegistroEmpresas() { DB::beginTransaction(); try { $empresa = new LandingEmpresa(); $empresa->razon_social = ucwords(strtolower(Input::get('empresa_razonsocial'))); $empresa->ruc = Input::get('empresa_ruc'); $empresa->inscritos = Input::get('empresa_inscritos'); $empresa->domicilio = Input::get('empresa_domicilio'); $empresa->email = Input::get('empresa_email'); $empresa->telefono = Input::get('empresa_telefono'); $empresa->celular = Input::get('empresa_celular'); $empresa->curso = Input::get('empresa_curso'); $empresa->comentario = Input::get('empresa_comentario'); $empresa->recibir_noticias = Input::get('empresa_informacion'); $empresa->ip = Request::getClientIp(true); $empresa->save(); $respuesta = array('status' => 'ok'); DB::commit(); } catch (\Exception $e) { DB::rollback(); $respuesta = array('status' => 'error', 'messages' => 'Exception with msg: ' . $e->getMessage()); } return Response::json($respuesta, 200); }
public function newCategory() { $validate = new Validate(); $validated = $validate->Validate_Category(); $nameToSlug = $this->nameToSlug($validated); if (\Auth::check()) { if ($validated->passes() && $nameToSlug === true) { $slug = \Input::get('name'); $slug = preg_replace('#[ -]+#', '-', $slug); $slug = strtolower($slug); \DB::beginTransaction(); try { $item = new \MenuCategory(); $item->menu_category_name = \Input::get('name'); $item->menu_category_slug = $slug; $item->save(); } catch (ValidationException $e) { DB::rollback(); throw $e; } \DB::commit(); return \Redirect::to('admin/category/edit/' . $slug)->with('message', '<div class="alert alert-dismissible alert-success alert-link"><button type="button" class="close" data-dismiss="alert">×</button>Saved!</p></div>'); } if ($nameToSlug === false) { return \View::make('categories.new')->withErrors($validated)->withInput(array('name'))->with('message', '<p class="alert alert-dismissible alert-danger alert-link">That category already exists!'); } return \View::make('categories.new')->withErrors($validated)->withInput(array('name')); } return \Redirect::to('admin'); }
public function deleteCategoryInfo($slug) { $results = \MenuCategory::where('menu_category_slug', '=', $slug)->get(); foreach ($results as $result) { $id = $result->menu_category_id; } $items_using_cat = \MenuItem::where('menu_item_category_fk', '=', $id)->get(); foreach ($items_using_cat as $item_using_cat) { if ($item_using_cat) { return \Redirect::to("admin/category/edit/{$slug}")->with('message', '<div class="alert alert-dismissible alert-danger alert-link">Unable to delete category. Please make sure no items are using this category.</p></div>'); } } //if an item exists that has this cat's fk, reload the page with an error if (\Auth::check()) { \DB::beginTransaction(); try { $statement = \MenuCategory::find($id); $statement->delete(); } catch (ValidationException $e) { DB::rollback(); throw $e; } \DB::commit(); return \Redirect::to('admin')->with('message', '<div class="alert alert-dismissible alert-success alert-link">Category has been deleted</p></div>'); } return \Redirect::to('admin'); }
public function postAdminSettings() { $title = Input::get('title'); $about = Input::get('about'); $address = Input::get('address'); $phone = Input::get('phone'); $email = Input::get('email'); $location = Input::get('location'); $file = Input::file('file'); $destinationPath = 'uploads'; $filename = DB::table('settings')->first()->logo; // If the uploads fail due to file system, you can try doing public_path().'/uploads' if ($file) { $filename = time() . $file->getClientOriginalName(); $extension = $file->getClientOriginalExtension(); $upload_success = Input::file('file')->move($destinationPath, $filename); } DB::beginTransaction(); try { DB::table('settings')->where('id', 1)->update(array('title' => $title, 'logo' => $filename, 'about' => $about, 'address' => $address, 'phone' => $phone, 'email' => $email, 'location' => $location)); DB::commit(); return Redirect::route('getAdminSettings')->with(array('status' => 'success')); } catch (\Exception $e) { DB::rollback(); return Redirect::route('getAdminSettings')->with(array('status' => 'error')); } }
public function updateRestaurantInfo() { $user = \Auth::user(); $id = $user->user_id; $restaurant = \Restaurant::all(); foreach ($restaurant as $rest) { $restaurant_name = $rest->restaurant_name; $restaurant_street_1 = $rest->restaurant_street_1; $restaurant_street_2 = $rest->restaurant_street_2; $restaurant_phone = $rest->restaurant_phone; $restaurant_email = $rest->restaurant_email; $restaurant_id = $rest->restaurant_info_id; } \DB::beginTransaction(); try { $statement = \Restaurant::find($restaurant_id); $statement->restaurant_name = \Input::get('name'); $statement->restaurant_street_1 = \Input::get('address1'); $statement->restaurant_street_2 = \Input::get('address2'); $statement->restaurant_email = \Input::get('email'); $statement->restaurant_phone = \Input::get('phone'); $statement->user_id_fk = $id; $statement->save(); } catch (ValidationException $e) { DB::rollback(); throw $e; } \DB::commit(); return \Redirect::to('admin/account/edit/restaurant')->withRestaurantName($restaurant_name)->withRestaurantStreet_1($restaurant_street_1)->withRestaurantStreet_2($restaurant_street_2)->withRestaurantPhone($restaurant_phone)->withRestaurantEmail($restaurant_email)->with('message', '<p class="alert alert-dismissible alert-success alert-link">Saved!' . '</p>'); }
/** * Update the specified resource in storage. * POST /cargo/editar * * @return Response */ public function postEditar() { if (Request::ajax()) { $sql = ""; $cargoId = Input::get('id'); $array = array(); $array['grupo_persona_id'] = Input::get('grupop'); $array['cargo_estrategico_id'] = Input::get('cargo'); $cargo_estrategico = Input::get('cargo'); $array['id'] = $cargoId; DB::beginTransaction(); DB::table('grupos_cargos')->where('grupo_persona_id', Input::get('grupop'))->update(array('estado' => 0)); for ($i = 0; $i < count($cargo_estrategico); $i++) { $sql = " SELECT id\n FROM grupos_cargos\n WHERE grupo_persona_id='" . Input::get('grupop') . "'\n AND cargo_estrategico_id='" . $cargo_estrategico[$i] . "'"; $rf = DB::select($sql); if (count($rf) > 0) { $cargo = GrupoCargo::find($rf[0]->id); $cargo->fecha_inicio = Input::get('fecha_inicio'); $cargo->estado = 1; $cargo->usuario_updated_at = Auth::user()->id; $cargo->save(); } else { $cargo = new GrupoCargo(); $cargo->grupo_persona_id = Input::get('grupop'); $cargo->cargo_estrategico_id = $cargo_estrategico[$i]; $cargo->fecha_inicio = Input::get('fecha_inicio'); $cargo->estado = 1; $cargo->usuario_created_at = Auth::user()->id; $cargo->save(); } } DB::commit(); return Response::json(array('rst' => 1, 'msj' => 'Registro actualizado correctamente')); } }
public function postValidar() { if (Request::ajax()) { $personas = Input::get('personas'); DB::beginTransaction(); for ($i = 0; $i < count($personas); $i++) { $per = explode("_", $personas[$i]); $mensajeria = Mensajeria::where('activista_id', $per[1])->first(); if (!isset($mensajeria->id)) { $mensajeria = new Mensajeria(); $mensajeria->activista_id = $per[1]; $mensajeria->usuario_created_at = $this->userID; } else { $mensajeria->usuario_updated_at = $this->userID; } if ($per[0] == 'celular') { $mensajeria->cel = $per[2]; $mensajeria->nrollamada = $mensajeria->nrollamada * 1 + 1; } else { $mensajeria->email = 1; $mensajeria->validado = 1; } $mensajeria->save(); } DB::commit(); return Response::json(array('rst' => 1, 'msj' => 'Se registro correctamente')); } }
public function __construct(\App\Myclasses\Checks\Checker $checker) { \DB::beginTransaction(); $this->fail = 0; $this->checker = $checker; $this->data = $this->checker->getData(); }
public function criar(array $dados) { \DB::beginTransaction(); try { $dados['status'] = 0; if (isset($dados['codigo_cupom'])) { $cupom = $this->cupomRepository->findByField('codigo', $dados['codigo_cupom'])->first(); $dados['cupom_id'] = $cupom->id; $cupom->used = 1; $cupom->save(); unset($dados['codigo_cupom']); } $items = $dados['items']; unset($dados['items']); $pedido = $this->repository->create($dados); $total = 0; foreach ($items as $item) { $item['preco'] = $this->produtoRepository->find($item['produto_id'])->preco; $pedido->items()->create($item); $total += $item['preco'] * $item['quantidade']; } $pedido->total = $total; if (isset($cupom)) { $pedido->total = $total - $cupom->valor; } $pedido->save(); \DB::commit(); return $pedido; } catch (\Exception $e) { DB::rollback(); throw $e; } }
public function store(StoreDocumentRequest $request) { $data = $request->all(); $document = $this->storeService->tracking($data['document_id']); if (!empty($data['zero'])) { $this->orderRepository->create($data); } else { if ($document['status'] == 2) { \DB::beginTransaction(); try { $data['evaluation'] = $this->storeService->evaluation($data); $this->orderRepository->create($data); $this->storeService->care($data['document_id']); \DB::commit(); } catch (\Exception $e) { \DB::rollback(); throw $e; } } else { \DB::beginTransaction(); try { $data['evaluation'] = $this->storeService->evaluation($data); $this->orderRepository->create($data); \DB::commit(); } catch (\Exception $e) { \DB::rollback(); throw $e; } } } Session::put('success', 'Corrigida com sucesso'); return redirect()->route('store.index'); }
public function saveBook(Request $request) { \DB::beginTransaction(); $this->cover = $this->upload($request); $this->title = $request->input('title'); $this->author = $request->input('author'); $this->translator = $request->input('translator'); $this->synopsis = $request->input('synopsis'); $this->origin = $request->input('origin'); $this->publishing_companies_id = $request->input('publishing_companies_id'); $this->language = $request->input('language'); $this->edition = $request->input('edition'); $this->year = $request->input('year'); $this->bar_code = $request->input('bar_code'); $this->isbn = $request->input('isbn'); $this->binding = $request->input('binding'); $this->height = floatval(str_replace(',', '.', $request->input('height'))); $this->width = floatval(str_replace(',', '.', $request->input('width'))); $this->length = floatval(str_replace(',', '.', $request->input('length'))); $this->weight = floatval(str_replace(',', '.', $request->input('weight'))); $this->number_pages = $request->input('number_pages'); if ($this->save()) { $this->genus()->sync($request->input('genus')); $success = true; } if ($success) { \DB::commit(); return true; } else { \DB::rollback(); return false; } }
public function postRegister(Request $request) { $dataClient = $request->only('name', 'last_name', 'phone', 'email'); $dataUser = $request->only('email', 'password'); $dataClientAddress = $request->only('id_city', 'address', 'latitude', 'longitude'); $validator = \Validator::make($dataClient, $this->rulesClient); if ($validator->passes()) { try { \DB::beginTransaction(); $dataUser['name'] = $dataClient['name'] . ' ' . $dataClient['last_name']; $dataUser['type'] = 'client'; $user = $this->userRepo->create($dataUser); $dataClient['id_user'] = $user->id; $client = $this->clientRepo->create($dataClient); $dataClientAddress['id_client'] = $client->id; $clientAddress = $this->clientAddressRepo->create($dataClientAddress); $code = 201; $message = "Cliente Registrado Corectamente"; $success = true; \DB::commit(); return response()->json(compact('success', 'message', 'client'), $code); } catch (\Exception $e) { \DB::rollback(); $code = 500; $success = false; $message = 'Error al registrar'; return response()->json(compact('success', 'message'), $code); } } else { $success = false; $message = $validator->messages(); $code = 400; return response()->json(compact('success', 'message'), $code); } }
public function updateBroadcasterProfile($request) { if ($request->hasFile('logo')) { $file = $request->file('logo'); $logo = time() . "-" . $file->getClientOriginalName(); $file->move(public_path() . \Config::get('site.broadcasterLogoPath'), $logo); $this->currentBroadcaster->logo = $logo; } $success = false; \DB::beginTransaction(); try { $this->currentUser->name = $request->get('name'); if ($request->get('changepass')) { $this->currentUser->password = \Hash::make(trim($request->get('password'))); } $this->currentUser->save(); $this->currentBroadcaster->display_name = $request->get('display_name'); $this->currentBroadcaster->company_name = $request->get('company_name'); $this->currentBroadcaster->save(); $success = true; } catch (\Exception $e) { \DB::rollback(); } if ($success) { \DB::commit(); } }
public function __construct($object, $data) { $this->data = $data; \DB::beginTransaction(); try { switch ($object) { case 'star': $this->toChange = \App\Star::find($data['id']); $this->address = $this->toChange->address; $this->changeStar(); $this->finalize(); break; case 'planet': $this->toChange = \App\Planet::find($data['id']); $this->address = $this->toChange->star->address; $this->changePlanet(); $this->finalize(); break; case 'bari': $this->toChange = \App\Bariplanet::find($data['id']); $this->address = $this->toChange->center->address; $this->changePlanet(); $this->finalize(); break; case 'multi': $this->toChange = \App\Baricenter::find($data['id']); $this->address = $this->toChange->address; $this->changeMulti(); $this->finalize(); break; } } catch (\PDOException $e) { $this->rollback(); } }
public function post_finalizar($venda) { $sqlVenda = "INSERT INTO vendas (idCliente,idVendedor,dataVenda) VALUES (:idCliente,:idVendedor,:dataVenda)"; $sqlItemVenda = "INSERT INTO itensVenda (idVenda,idProduto,quantidade,precoUnitario) VALUES (:idVenda,:idProduto,:quantidade,:precoUnitario)"; try { DB::beginTransaction(); $stmtVendas = DB::prepare($sqlVenda); $stmtVendas->bindParam("idCliente", $venda->idCliente); $stmtVendas->bindParam("idVendedor", $venda->idVendedor); $stmtVendas->bindParam("dataVenda", DB::dateToMySql($venda->data)); $stmtVendas->execute(); $venda->idVenda = DB::lastInsertId(); foreach ($venda->itens as $item) { $stmtItem = DB::prepare($sqlItemVenda); $stmtItem->bindParam("idVenda", $venda->idVenda); $stmtItem->bindParam("idProduto", $item->idProduto); $stmtItem->bindParam("quantidade", $item->quantidade); $stmtItem->bindParam("precoUnitario", $item->preco); $stmtItem->execute(); } DB::commit(); } catch (Exception $exc) { DB::rollBack(); throw new Exception($exc->getMessage()); } return $venda; }
public function commission($driver, $ipn) { try { \DB::beginTransaction(); if ($driver->id == $ipn['custom']) { // Get the pre-month commissions. $sales = new SaleCollection($driver->sales(Carbon::now()->subMonth(), Carbon::now())); if ($sales) { $paypalHelper = new PaypalHelper($driver); // get authorized commission payment if ($authorizedCommissionPayment = $paypalHelper->createPaypalFuturePayment($sales->toArray()['totals'])) { // capture authorized commission payment if ($capture = $paypalHelper->capturePaypalPayment($authorizedCommissionPayment)) { if ($authorizedCommissionPayment['id'] == $capture['parent_payment']) { $commission_payment = ['driver_id' => $driver->id, 'commissions' => $authorizedCommissionPayment['transactions'][0]['amount']['total'], 'currency' => $authorizedCommissionPayment['transactions'][0]['amount']['currency'], 'status' => $authorizedCommissionPayment['state'], 'commission_ipn' => $authorizedCommissionPayment, 'commission_payment_id' => $authorizedCommissionPayment['id'], 'capture_id' => $capture['id'], 'capture_created_at' => $capture['create_time'], 'capture_updated_at' => $capture['update_time'], 'capture_status' => $capture['state'], 'capture_ipn' => $capture]; if ($commission = EloquentCommissionRepository::create($commission_payment)) { \DB::commit(); // Todo:: fire notification event the commission paid. $commission->type = "billing"; \Event::fire('paxifi.notifications.billing', [$commission]); return $this->setStatusCode(201)->respondWithItem($commission); } } } } } } } catch (\Exception $e) { return $this->setStatusCode(400)->respondWithError($e->getMessage()); } }
/** * Create the shipment for sticker. * * @param null $driver * * @return \Illuminate\Http\JsonResponse */ public function shipment($driver = null) { try { \DB::beginTransaction(); if (is_null($driver)) { $driver = $this->getAuthenticatedDriver(); } $new_shipment = ["sticker_id" => $driver->sticker->id, "address" => \Input::get('address', $driver->address), "status" => "waiting", "paypal_payment_status" => "pending"]; with(new CreateShipmentValidator())->validate($new_shipment); // Add paypal_metadata_id for future payment. $driver->paypal_metadata_id = \Input::get('metadata_id'); if ($capturedPayment = $this->paypal->buySticker($driver)) { $new_shipment['paypal_payment_id'] = $capturedPayment->parent_payment; if ($shipment = Shipment::create($new_shipment)) { \DB::commit(); return $this->setStatusCode(201)->respondWithItem($shipment); } return $this->errorInternalError('Shipment for buying sticker created failed.'); } return $this->errorInternalError(); } catch (ValidationException $e) { return $this->errorWrongArgs($e->getErrors()); } catch (\Exception $e) { print_r($e->getMessage()); return $this->errorInternalError(); } }
function changeEmail() { $validator = new Validate(); $validated = $validator->validateNewEmail(); $user = \Auth::user(); $email = $user->email; if ($validated->fails()) { return \View::make('accounts.email')->withErrors($validated)->withEmail($email); } if (\Auth::check()) { $id = \Auth::user()->user_id; \DB::beginTransaction(); try { $statement = \User::find($id); $statement->email = \Input::get('email'); $statement->save(); } catch (ValidationException $e) { DB::rollback(); throw $e; } \DB::commit(); return \Redirect::to('admin/account/edit/email')->with('message', '<p class="alert alert-dismissible alert-success alert-link">Email address updated. </p>')->withEmail($email); } return \Redirect::to('admin/account/edit/email')->with('message', '<p class="alert alert-dismissible alert-success alert-link">Email address updated. </p>')->withEmail($email); }
public function create(array $data) { try { \DB::beginTransaction(); $teacherTraitData = array(); $teacherTraitData['grade'] = $data['grade']; $teacherTrait = $this->teacherTraitRepo->create($teacherTraitData); $data = array_add($data, 'traits_id', $teacherTrait->id); $schoolData = array_only($data, ['school', 'zipcode']); if (App::environment('local')) { $password = '******'; } else { $password = str_random(16); } $activated = 1; $data['password'] = $password; $data['activated'] = $activated; $teacherData = array_only($data, ['first_name', 'last_name', 'email', 'title', 'traits_id', 'password', 'activated']); $teacher = $this->teacherRepo->create($teacherData); $school = $this->schoolRepo->findOrCreate($schoolData); $teacher->schools()->attach($school->id); \Event::fire('user.created', [$teacher, $password]); \DB::commit(); return true; } catch (\Exception $ex) { \Log::error($ex); \DB::rollback(); return false; } }
public function create(array $data) { DB::beginTransaction(); try { $data['status'] = 0; if (isset($data['cupom_code'])) { $cupom = $this->cupomRepository->findByField('code', $data['cupom_code'])->first(); $data['cupom'] = $cupom->id; $cupom->used = 1; $cupom->save(); unset($data['cupom_code']); } $items = $data['items']; unset($data['items']); $order = $this->orderRepository->create($data); $total = 0; foreach ($items as $item) { $item['price'] = $this->productRepository->find($item['product_id'])->price; $order->items()->create($item); $total += $item['price'] * $item['qtd']; } $order->total = $total; if (isset($cupom)) { $order->total = $total - $cupom->value; } $order->save(); \DB::commit(); } catch (\Exception $e) { \DB::rollback(); throw $e; } }
public function responder() { try { DB::beginTransaction(); $data = Input::all(); $new = $data; unset($new['apikey']); unset($new['session_key']); if (isset($new["respuesta"])) { foreach ($new["respuesta"] as $i => $r) { $respuesta = array("paciente_id" => $new["paciente_id"], "anamnesis_pregunta_id" => $new["pregunta"][$i], "respuesta" => $r); $AR = AnamnesisRespuesta::create($respuesta); if ($AR->save()) { $this->eventoAuditar($AR); } else { DB::rollback(); return Response::json(array('error' => true, 'mensaje' => HerramientasController::getErrores($AR->validator), 'listado' => $data), 200); } } DB::commit(); return Response::json(array('error' => false, 'listado' => $new), 200); } } catch (\Exception $e) { DB::rollback(); return Response::json(array('error' => true, 'mensaje' => $e->getMessage()), 200); } }
public function setUp() { parent::setUp(); Artisan::call('migrate'); DB::beginTransaction(); $this->repo = (new BaseRepositoryEloquent())->setModel(new User()); }
public function postSchimbaStadiu($id_livrabil) { $actualizare_ore = Input::get('ore_lucrate') > 0; $is_stadiu = Input::get('stadiu_selectionat') != null && Input::get('stadiu_selectionat') > 0; $array_update = array(); if ($is_stadiu) { //Face insert in tabela de istoric de stadii //Actualizeaza stadiul livrabilului $array_update = array_add($array_update, 'id_stadiu', Input::get('stadiu_selectionat')); } if ($actualizare_ore) { //Actualizeaza numarul de ore lucrate la acest livrabil $array_update = array_add($array_update, 'ore_lucrate', Input::get('ore_lucrate')); } // Start transaction! DB::beginTransaction(); if ($is_stadiu) { try { DB::table('istoric_stadii_livrabil')->insertGetId(array('id_livrabil_etapa' => Input::get('id_livrabil_etapa'), 'id_stadiu' => Input::get('stadiu_selectionat'), 'id_user' => Entrust::user()->id)); } catch (Exception $e) { DB::rollback(); return Redirect::back()->with('message', 'Eroare salvare date: ' . $e); } } if ($is_stadiu || $actualizare_ore) { try { DB::table('livrabile_etapa')->where('id', Input::get('id_livrabil_etapa'))->update($array_update); } catch (Exception $e) { DB::rollback(); return Redirect::back()->with('message', 'Eroare salvare date: ' . $e); } } DB::commit(); return Redirect::back()->with('message', 'Actualizare realizata cu succes!')->withInput(); }
/** * Store a newly created resource in storage. * * @return Response */ public function store($quiz_id) { try { DB::beginTransaction(); $quiz = Quiz::find($quiz_id); foreach (Input::get('question') as $input_question) { $question_params = array("name" => $input_question['name']); $question_validator = Question::validate($question_params); if ($question_validator->fails()) { throw new Exception("Question can't be saved"); } $question = new Question($question_params); $question = $quiz->questions()->save($question); foreach ($input_question['options'] as $value) { $option_params = array("name" => $value['name'], "is_correct" => array_key_exists("is_correct", $value) ? true : false); $option_validator = Option::validate($option_params); if ($option_validator->fails()) { throw new Exception("Option can't be saved"); } $option = new Option($option_params); $option = $question->options()->save($option); } } DB::commit(); return Redirect::to("quizzes/" . $quiz->id . '/questions'); } catch (Exception $e) { DB::rollback(); //throw new Exception($e); return Redirect::to('quizzes/' . $quiz->id . '/questions/create'); } }
function changePassword() { $validator = new Validate(); $validated = $validator->validateNewPassword(); if ($validated->fails()) { return \View::make('accounts.password')->withErrors($validated); } if (\Auth::check()) { $hashed = \Hash::make(\Input::get('password')); $id = \Auth::user()->user_id; \DB::beginTransaction(); try { $statement = \User::find($id); $statement->password = $hashed; $statement->save(); } catch (ValidationException $e) { DB::rollback(); throw $e; } \DB::commit(); \Auth::logout(); return \Redirect::to('admin/logout')->with('message', '<div class="alert alert-dismissible alert-success alert-link"> <button type="button" class="close" data-dismiss="alert">×</button> Password changed. Please log in. </div>'); } return \Redirect::to('admin')->with('message', '<div class="alert alert-dismissible alert-success alert-link"> <button type="button" class="close" data-dismiss="alert">×</button> Password changed. Please log in. </div>'); }
/** * Creates a new entry, puts the id into the session and * redirects back to the index page. */ public function store() { if (Entry::canCreateOrEdit() === false) { return Redirect::route('entry.index')->withMessage("Sorry, the competition has now started and new entries cannot be created."); } $input = Input::all(); $validator = Validator::make($input, Entry::$entry_rules); if ($validator->fails()) { return Redirect::route('entry.create')->withInput()->withErrors($validator); } DB::beginTransaction(); $entry = new Entry(); $entry->email = $input['email']; $entry->secret = Hash::make($input['secret']); $entry->confirmation = uniqid('', true); $entry->first_name = $input['first_name']; $entry->last_name = $input['last_name']; $entry->peer_group = $input['peer_group']; $entry->save(); $matches = Match::all(); foreach ($matches as $match) { $match_prediction = new MatchPrediction(); $match_prediction->team_a = $match->team_a; $match_prediction->team_b = $match->team_b; $match_prediction->pool = $match->pool; $match_prediction->match_date = $match->match_date; $entry->matchPredictions()->save($match_prediction); } DB::commit(); $this->sendConfirmationEmail($entry); $this->putEntryIdIntoSession($entry->id); return View::make('entry.edit')->with('entry', $entry); }
/** * Create order record. * * @return \Illuminate\Http\JsonResponse */ public function store() { try { \DB::beginTransaction(); $items = Collection::make(\Input::get('items')); $order = new Order(); // create the order $order->save(); // Attach items to order $items->each(function ($item) use($order) { $order->addItem($item); }); // Calculate commission & profit /** @var \Paxifi\Support\Commission\CalculatorInterface $calculator */ $calculator = \App::make('Paxifi\\Support\\Commission\\CalculatorInterface'); $calculator->setCommissionRate($order->OrderDriver()->getCommissionRate()); $order->setCommission($calculator->calculateCommission($order)); $order->setProfit($calculator->calculateProfit($order)); // save order $order->save(); \DB::commit(); return $this->setStatusCode(201)->respondWithItem(Order::find($order->id)); } catch (ModelNotFoundException $e) { return $this->errorWrongArgs('Invalid product id'); } catch (\InvalidArgumentException $e) { return $this->errorWrongArgs($e->getMessage()); } catch (\Exception $e) { return $this->errorInternalError(); } }
public function save() { $id = Input::get('id'); $tt = $this->gioithieu->find($id); $token = \Input::get('_token'); if (\Session::token() === $token) { $data = array('stt' => Input::get('stt'), 'luotxem' => Input::get('luotxem'), 'ten_vi' => Input::get('ten_vi'), 'mota_vi' => Input::get('mota_vi'), 'noidung_vi' => Input::get('noidung_vi'), 'hienthi' => Input::has('hienthi'), 'noibat' => Input::has('noibat'), 'slug_vi' => \Str::slug(Input::get('ten_vi'), '-'), 'title_seo_vi' => Input::get('title_seo_vi'), 'desc_seo_vi' => Input::get('desc_seo_vi'), 'keyword_seo_vi' => Input::get('keyword_seo_vi')); $tt->stt = $data['stt']; $tt->luotxem = $data['luotxem']; $tt->hienthi = $data['hienthi']; $tt->noibat = $data['noibat']; $tt->ten_vi = $data['ten_vi']; $tt->slug_vi = $data['slug_vi']; $tt->mota_vi = $data['mota_vi']; $tt->noidung_vi = $data['noidung_vi']; $tt->title_seo_vi = $data['title_seo_vi']; $tt->desc_seo_vi = $data['desc_seo_vi']; $tt->keyword_seo_vi = $data['keyword_seo_vi']; if (Input::hasFile('photo')) { // LAY TEN FILE $filename = \Str::random(20) . '_' . Input::file('photo')->getClientOriginalName(); // THU MUC UPLOAD TIN TUC $directory = \Config::get('detr.gioithieu_upload'); $upload_status = Input::file('photo')->move(public_path() . $directory, $filename); chmod(public_path() . $directory . $filename, 0755); if ($upload_status) { //UPload thanh cong, kiem tra xem file photo co ton tai hay khong, neu cos thi xoa di if (\File::exists(public_path() . $tt->photo)) { \File::delete(public_path() . $tt->photo); } $tt->photo = $directory . $filename; if (\File::exists(public_path() . '/' . $tt->thumb)) { \File::delete(public_path() . '/' . $tt->thumb); } $thumb = \Illuminage::image($directory . $filename)->thumbnail(200, 200)->getRelativePath(); $tt->thumb = $thumb; chmod(public_path() . $thumb, 0755); } } /* avoiding resubmission of same content */ if (count($tt->getDirty()) > 0) { //Transaction \DB::beginTransaction(); try { $tt->save(); } catch (\Exception $e) { \DB::rollback(); return \Redirect::back()->with('success', 'Tin tức cập nhật thất bại!'); } \DB::commit(); //Transaction return \Redirect::back()->with('success', 'Tin tức đã được cập nhật!'); } else { return \Redirect::back()->with('success', 'Nothing to update!'); } } else { return \Redirect::back()->withInput()->with('success', 'Cập nhật thất bại, Token hết hiệu lực'); } }
/** * @SWG\Operation( * partial="usuarios.store", * summary="Guarda un usuario", * type="users", * * @SWG\Parameter( * name="body", * description="Objeto Usuario que se necesita para guardar", * required=true, * type="User", * paramType="body", * allowMultiple=false * ), * ) */ public function store() { log::info("creacion usuario"); $data = Input::all(); $nombre = isset($data['usuario']['nombre']) ? $data['usuario']['nombre'] : ''; $ap = isset($data['usuario']['apellido_paterno']) ? $data['usuario']['apellido_paterno'] : ''; $am = isset($data['usuario']['apellido_materno']) ? $data['usuario']['apellido_materno'] : ''; $id_tipo_donador = isset($data['usuario']['id_tipo_donador']) ? $data['usuario']['id_tipo_donador'] : ''; $donacion = isset($data['usuario']['donacion_info']) ? $data['usuario']['donacion_info'] : ''; $username = isset($data['usuario']['username']) ? $data['usuario']['username'] : ''; $password = isset($data['usuario']['password']) ? $data['usuario']['password'] : ''; log::info(var_export($data, true)); //die(); if (!$data['usuario']) { return false; } $usuario = User::select('username')->where('username', '=', $data['usuario']['username'])->first(); if (count($usuario) > 0) { return Response::json(array('error' => "500", 'error_message' => "Ya existe un usuario con esta cuenta")); } else { DB::beginTransaction(); try { $usuarioInfo = new UserInfo(); $usuarioInfo->nombre = trim($nombre); $usuarioInfo->apellido_paterno = trim($ap); $usuarioInfo->apellido_materno = trim($am); $usuarioInfo->id_tipo_donador = trim($id_tipo_donador); $usuarioInfo->donacion_info = trim($donacion); $usuarioInfo->save(); log::info("inseted"); log::info($usuarioInfo); if ($data['usuario']['contacto']) { $usuario = UserInfo::find($usuarioInfo->id_usuario_info); $arrContactos = array(); log::info("find"); log::info($usuario); log::info("contacto"); log::info($usuario->contactos); $usuario->contactos()->detach(); if ($data['usuario']['contacto'] && is_array($data['usuario']['contacto'])) { foreach ($data['usuario']['contacto'] as $value) { $arrContactos[] = array('id_tipo_contacto' => $value['tipo'], 'dato' => $value['valor']); } } $usuario->contactos()->attach($arrContactos); } $login = new User(); $login->username = trim($username); $login->password = md5(trim($password)); $login->id_usuario_info = $usuarioInfo->id_usuario_info; $login->save(); DB::commit(); return Response::json(array('error' => "200", 'error_message' => 'Se han guardado los datos')); } catch (Exception $ex) { return Response::json(array('error' => "500", 'error_message' => $ex->getMessage())); DB::rollback(); } } }