/** * Add user * * @param array $user * @return boolean */ public function add(array $user) { $entity = new UserEntity(); $entity->setData($user); $repo = $this->store()->getRepository('user'); $event = $this->store()->getEvent(); if ($this->string()->length($event) > 0) { $event_after = 'OnBefore' . $this->string()->ucwords($event) . 'Add'; Event::on($event_after, function ($user) { $filter = array('LOGIC' => 'OR', UserEntity::C_LOGIN => $user[UserEntity::C_LOGIN], UserEntity::C_EMAIL => $user[UserEntity::C_EMAIL]); $copy = $this->finder()->filter($filter)->get(); if ($copy !== false) { $error = new MessageBag(); if ($copy->getValue(UserEntity::C_LOGIN) === $user[UserEntity::C_LOGIN]) { $error->add(UserEntity::C_LOGIN, $this->trans('user.manager.add.dublicate_login')); throw new ValidateException($error); } if ($copy->getValue(UserEntity::C_EMAIL) === $user[UserEntity::C_EMAIL]) { $error->add(UserEntity::C_EMAIL, $this->trans('user.manager.add.dublicate_email')); throw new ValidateException($error); } $error->add(UserEntity::C_LOGIN, $this->trans('user.manager.add.dublicate_login_or_email')); $error->add(UserEntity::C_EMAIL, $this->trans('user.manager.add.dublicate_login_or_email')); throw new ValidateException($error); } }); } if ($this->string()->length($event) > 0) { $event_after = 'OnAfter' . $this->string()->ucwords($event) . 'Add'; Event::on($event_after, function () { Cache::clearByTags('user'); }); } return $this->store()->add($repo, $entity); }
/** * @param string $key * @param string $message */ public static function add($key, $message) { if (!isset(self::$_messages)) { self::$_messages = new MessageBag(); } self::$_messages->add($key, $message); }
/** * Attempt to log in witth the credentials sent through Input * * @return \Illuminate\Http\RedirectResponse */ public function login() { $response = null; $identifier_field = Config::get('auth::user_table.login_through_field'); $password_field = 'password'; $credentials = [$identifier_field => Input::get($identifier_field), 'password' => Input::get($password_field), 'enabled' => true]; if (array_key_exists('email', $credentials)) { $credentials['email'] = strtolower($credentials['email']); } $rules = array(); $rules['password'] = '******'; if (array_key_exists('email', $credentials)) { $rules['email'] = 'required|email|exists:' . Config::get('auth::user_table.table_name'); } if (array_key_exists('username', $credentials)) { $rules['username'] = '******' . Config::get('auth::user_table.table_name'); } $validator = \Validator::make($credentials, $rules); if ($validator->fails()) { return Redirect::back()->withInput()->withErrors($validator->errors()); } if (Auth::attempt($credentials, true)) { $response = Redirect::intended('/')->with('success'); } else { $errors = new MessageBag(); if (empty($credentials[$identifier_field])) { $errors->add('message', trans('auth::form.login failed')); } else { $errors->add('message', trans('auth::form.login failed_with_username', ['username' => $credentials[$identifier_field]])); } $response = Redirect::back()->withInput()->withErrors($errors); } return $response; }
public function addMessage($key, $message) { if (!$this->messageBag) { $this->messageBag = new MessageBag(); } $this->messageBag->add($key, $message); }
function saving($model) { $errors = new MessageBag(); /////////// // RULES // /////////// if (is_null($model->_id)) { $id = 0; } else { $id = $model->_id; } ////////////// // VALIDATE // ////////////// $client = Client::key($model->key)->where('_id', '<>', $id)->first(); if ($client) { $errors->add('Key', 'Key must be unique'); } $client = Client::secret($model->key)->where('_id', '<>', $id)->first(); if ($client) { $errors->add('Secret', 'Secret must be unique'); } if ($errors->count()) { $model->setErrors($errors); return false; } }
/** * observe Calendar event deleting * 1. delete child * 2. delete chart * 3. delete schedule * 4. act, accept or refuse * * @param $model * @return bool */ public function deleting($model) { $errors = new MessageBag(); //1. delete child foreach ($model->calendars as $key => $value) { if (!$value->delete()) { $errors->add('Calendar', $value->getError()); } } //2. delete chart foreach ($model->follows as $key => $value) { if (!$value->delete()) { $errors->add('Calendar', $value->getError()); } } //3. delete schedule foreach ($model->schedules as $key => $value) { if (!$value->delete()) { $errors->add('Calendar', $value->getError()); } } if ($errors->count()) { $model['errors'] = $errors; return false; } return true; }
/** * observe organisation event deleting * 1. delete branch * 2. delete chart * 3. delete policy * 4. act, accept or refuse * * @param $model * @return bool */ public function deleting($model) { $errors = new MessageBag(); //1. delete branch foreach ($model->branches as $key => $value) { //2. delete chart foreach ($value->charts as $key2 => $value2) { if (!$value2->delete()) { $errors->add('Organisation', $value2->getError()); } } if (!$value->delete()) { $errors->add('Organisation', $value->getError()); } } //3. delete policy foreach ($model->policies as $key => $value) { if (!$value->delete()) { $errors->add('Organisation', $value->getError()); } } if ($errors->count()) { $model['errors'] = $errors; return false; } return true; }
/** * Run the validation on the rules in the array * @return boolean */ public function passes() { $validation = Validator::make($this->data, $this->rules); if ($validation->fails()) { foreach ($validation->messages()->all() as $error) { $this->messages->add('error', $error); } return false; } return true; }
/** * Check that the contents of POST are valid for this model * @return boolean */ public function isValid() { $validation = Validator::make(Input::all(), static::$rules); if ($validation->fails()) { foreach ($validation->messages()->all() as $error) { $this->errors->add('error', $error); } return false; } return true; }
public function testFormatIsRespected() { $container = new MessageBag(); $container->setFormat('<p>:message</p>'); $container->add('foo', 'bar'); $container->add('boom', 'baz'); $this->assertEquals('<p>bar</p>', $container->first('foo')); $this->assertEquals(array('<p>bar</p>'), $container->get('foo')); $this->assertEquals(array('<p>bar</p>', '<p>baz</p>'), $container->all()); $this->assertEquals('bar', $container->first('foo', ':message')); $this->assertEquals(array('bar'), $container->get('foo', ':message')); $this->assertEquals(array('bar', 'baz'), $container->all(':message')); }
public function testRequirements() { $messages = new MessageBag(); $requirements = $this->getDefinition()->getAllRequirements(); foreach ($requirements as $requirement) { $requirement = app($requirement); if ($requirement->test()) { $messages->add('success', $requirement->getSuccess()); } else { $messages->add('error', $requirement->getError()); } } return $messages; }
/** * set pasword * * 1. get activation link * 2. validate activation * @param activation link * @return array of employee */ public function setPassword($activation_link) { if (!Input::has('activation')) { return new JSend('error', (array) Input::all(), 'Tidak ada data activation.'); } $errors = new MessageBag(); DB::beginTransaction(); //1. Validate activation Parameter $activation = Input::get('activation'); //1. get activation link $employee = Employee::activationlink($activation_link)->first(); if (!$employee) { $errors->add('Activation', 'Invalid activation link'); } //2. validate activation $rules = ['password' => 'required|min:8|confirmed']; $validator = Validator::make($activation, $rules); if ($validator->passes()) { $employee->password = $activation['password']; $employee->activation_link = ''; if (!$employee->save()) { $errors->add('Activation', $employee->getError()); } } else { $errors->add('Activation', $validator->errors()); } if ($errors->count()) { DB::rollback(); return new JSend('error', (array) Input::all(), $errors); } DB::commit(); return new JSend('success', ['employee' => $employee->toArray()]); }
protected function logMailErrors() { $this->order->getConnection()->getPdo()->rollback(); $this->errors->add("email", "There was an error sending the email."); Log::error('error sending email.'); throw new InvalidException(); }
public function index() { Breadcrumbs::addCrumb('Cadastrar', Request::fullUrl()); $signupForm = new SignupForm(['data' => Input::all(), 'prefix' => 'signup']); $errors = new MessageBag(); if (Input::method() == 'POST') { if ($signupForm->isValid()) { try { DB::beginTransaction(); $user = new User(); $user->name = $signupForm->fullName->value; $user->email = $signupForm->email->value; $user->password = Hash::make($signupForm->password->value); if ($user->save()) { Mail::send('user_panel::mails.welcome', ['user' => $user], function ($message) use($user) { $message->to($user->email)->subject('Seja bem vindo'); }); DB::commit(); return Redirect::route('userpanel.signin')->with('success', 'Usuário cadastrado com sucesso!'); } else { $errors->add('other', 'Não foi possível cadastrar'); } } catch (Exception $e) { DB::rollback(); throw $e; } } else { $errors = $signupForm->errors(); } } return View::make('user_panel::front.register.index', compact('signupForm', 'errors')); }
/** * observe sale event saving * 1. generate ref number * 2. generate unique number * 3. create transact_at * 4. check voucher * 5. execute it there was no error * * @param $model * @return bool */ public function saving($model) { $errors = new MessageBag(); //1. Generate ref number $model->ref_number = $model->generateRefNumber($model); //2. Generate unique number if ($model->status == 'cart' || $model->status == 'na') { $model->unique_number = $model->generateUniqueNumber($model); } //3. create transact_at if (!in_array($model->status, ['canceled', 'abandoned', 'paid', 'shipping', 'delivered', 'na', 'wait', 'payment_process'])) { $model->transact_at = Carbon::now()->format('Y-m-d H:i:s'); } //4. check voucher if ($model->voucher_id != 0 && (!$model->voucher()->count() || $model->voucher->type == 'promo_referral')) { $errors->add('Voucher', 'Voucher tidak valid.'); } elseif ($model->voucher()->count()) { $result = $model->CountVoucherDiscount($model); if (!$result && count($model['errors'])) { return false; } else { $model->voucher_discount = $result; } } if ($errors->count()) { $model['errors'] = $errors; return false; } return true; }
public function sendPass() { $input = Input::all(); $user = User::where('email', '=', $input['email'])->first(); $errors = new MessageBag(); if ($user) { try { $user = $user->toArray(); $data['username'] = $user['username']; $data['token'] = $input['_token']; $data['firstname'] = $user['firstname']; $data['lastname'] = $user['lastname']; $data['email'] = $user['email']; Session::put('data', $data); Mail::send('mail.reset_' . App::getLocale(), $data, function ($message) { $message->to(session('data')['email'], session('data')['firstname'], session('data')['lastname'])->subject(trans('login.forgot')); }); DB::insert('INSERT INTO password_resets (email, token, created_at) values ' . '("' . $data['email'] . '", "' . $data['token'] . '", "' . time() . '")'); } catch (Exception $e) { $errors->add('reset', trans('message.trans')); return redirect()->back()->withErrors($errors); } Session::pull('data'); return redirect('login')->withErrors(['sent' => trans('message.sent')]); } else { Session::pull('data'); $errors->add('email', trans('message.email')); return redirect()->back()->withErrors($errors); } }
/** * Add error * @param string $key * @param string $message * @param array $params */ public function addError($key, $message, $params = []) { if ($this->error === null) { $this->error = new MessageBag(); } $this->error->add($this->string()->toUpper($key), !empty($params) ? strtr($message, $params) : $message); }
public static function storeCourse() { /**Запись и сохранение курса * в случае удачи - возвращаем true,иначе false * @return BooleanType * */ //Проверка радостей от пользователя $validator = Validator::make(array('name' => Input::get('name')), array('name' => array('required', 'min:5'))); if ($validator->passes()) { dd($validator); //Прошла валидация $course = new Course(); $course->name = Input::get('name'); $course->save(); //т.к у нас тепреь есть новая модель, //но контроллеры о ней ничего еще не знают- //положим упоминание о ней в Message Bag,чтоб они смогли прочитать $messageBag = new MessageBag(); $messageBag->add('courseId', $course->id); $message = 'Course ' . $course->name . ' been successful created'; $status = 'success'; $result = true; } else { //Все немного хуже и данные не валидны $message = 'Course not been successful created'; $status = 'fail'; $result = false; } //Вложим в сессию итог действия Session::put('message', $message); Session::put('status', $status); return $result; }
/** * Validates all fields with Laravel and custom rules * @param Request $request * @param array $passedRules * @return bool */ public function validate(Request $request, $passedRules = []) { $this->request = $request; //Collect rules from fields list($rules, $customFieldRules) = $this->collectRules(); //Combine passed rules with those extracted from fields $rules = array_merge($rules, $passedRules); //Make validator $validator = Validator::make($request->all(), $rules, $this->messages); //Set fields names for messages $validator->setAttributeNames($this->getAttributeNames()); //Run validation $validator->passes(); //Get messages $this->messageBag = $validator->messages(); //Do custom validation in fields ($field->customRules property) $customFieldRules = array_merge_recursive($customFieldRules, $this->customFieldRules); foreach ($customFieldRules as $fieldName => $rule) { foreach ($rule as $cr) { if ($message = $this->callCustomRules($cr, $request)) { $this->messageBag->add($fieldName, $message); } } } //Do custom validation in form class ($form->customRules property) foreach ($this->customRules as $fieldName => $cr) { if ($message = $this->callCustomRules($cr, $request)) { $this->messageBag->add($fieldName, $message); } } return $this->passed(); }
/** * Veritrans Credit Card * * 1. Check Order * 2. Save Payment * * @return Response */ public function veritranscc() { if (!Input::has('order_id')) { return new JSend('error', (array) Input::all(), 'Tidak ada data order id.'); } $errors = new MessageBag(); DB::beginTransaction(); //1. Validate Sale Parameter $order = Input::only('order_id', 'gross_amount', 'payment_type', 'masked_card', 'transaction_id'); //1a. Get original data $sale_data = \App\Models\Sale::findorfail($order['order_id']); //2. Save Payment $paid_data = new \App\Models\Payment(); $payment['transaction_id'] = $sale_data['id']; $payment['method'] = $order['payment_type']; $payment['destination'] = 'Veritrans'; $payment['account_name'] = $order['masked_card']; $payment['account_number'] = $order['transaction_id']; $payment['ondate'] = \Carbon\Carbon::parse($order['transaction_time'])->format('Y-m-d H:i:s'); $payment['amount'] = $order['gross_amount']; $paid_data = $paid_data->fill($payment); if (!$paid_data->save()) { $errors->add('Log', $paid_data->getError()); } if ($errors->count()) { DB::rollback(); return response()->json(new JSend('error', (array) Input::all(), $errors), 404); } DB::commit(); $final_sale = \App\Models\Sale::id($sale_data['id'])->with(['voucher', 'transactionlogs', 'user', 'transactiondetails', 'transactiondetails.varian', 'transactiondetails.varian.product', 'paidpointlogs', 'payment', 'shipment', 'shipment.address', 'shipment.courier', 'transactionextensions', 'transactionextensions.productextension'])->first()->toArray(); return response()->json(new JSend('success', (array) $final_sale), 200); }
public static function hydrateFromInput() { $className = get_called_class(); $reflectionMethod = new ReflectionMethod($className, '__construct'); $params = $reflectionMethod->getParameters(); $paramsToPass = []; $throwError = false; $errors = new MessageBag(); foreach ($params as $param) { $paramName = $param->getName(); if (\Input::has($paramName)) { $paramsToPass[] = \Input::get($paramName); } else { if (!$param->isOptional()) { $throwError = true; $errors->add('missing_parameters', $paramName); } } } if ($throwError) { throw new CommandParameterException($errors); } $reflect = new ReflectionClass($className); return $reflect->newInstanceArgs($paramsToPass); }
public function login(Request $request) { if (!empty($request->input('email'))) { $email = $request->input('email'); $password = $request->input('password'); $user_node = $this->users->getUser($email); // Create the Person model $user = new Person(); $user->setNode($user_node); if (!empty($user_node)) { // Check password and verification if (!$user->verified) { $message_bag = new MessageBag(); return redirect()->back()->with('errors', $message_bag->add('email', 'Dit emailadres is nog niet geverifieerd.')); } elseif (Hash::check($password, $user->password)) { Auth::login($user); // Register the event to Piwik $this->registerPiwikEvent($user->email, 'Login'); return redirect($this->redirectTo); } else { $message_bag = new MessageBag(); return redirect()->back()->with('errors', $message_bag->add('password', 'Het wachtwoord is incorrect.')); } } else { $message_bag = new MessageBag(); return redirect()->back()->with('errors', $message_bag->add('email', 'Het emailadres werd niet gevonden.')); } } else { $message_bag = new MessageBag(); return redirect()->back()->with('errors', $message_bag->add('email', 'Het emailadres werd niet gevonden.')); } }
public function postIndex() { $form = Form::fromFile(__DIR__ . '/contact.form.php'); $form->setInput(Input::all()); $validator = $form->accept(); if ($validator->fails()) { $form->setErrors($validator->messages()); return View::make('contact')->with('form', $form); } $data = $validator->getData(); // Get the label for an enum $data['found'] = $form->fieldSpec('found')['options'][$data['found']]; // Parse date inputs $data['from_date'] = strtotime($data['from_date']); $data['to_date'] = strtotime($data['to_date']); if (!Mail::send('emails.contact', $data, function ($message) use($data) { $message->to('*****@*****.**')->replyTo($data['email'], $data['person'])->subject('Contact form')->setCharset('UTF-8'); })) { $errors = new MessageBag(); // global here can be anything that's not an actual field name $errors->add('global', 'Could not send your contact request to contact@example.com. Please try again later.'); return View::make('contact')->with('form', $form)->with('errors', $errors); } return View::make('success'); }
public function delete() { $rules = array('newsletter_unsubscribe_email' => 'required|max:250|email|exists:fbf_newsletter_signups,email'); $validator = \Validator::make(\Input::all(), $rules, \Lang::get('laravel-newsletter-signup::copy.unsubscribe.validation')); if ($validator->fails()) { if (\Request::ajax()) { $messages = $validator->messages(); $message = $messages->first('newsletter_unsubscribe_email'); return \Response::JSON(array('message' => $message), 400); } return \Redirect::to(\Input::get('from'))->withInput()->withErrors($validator); } $signup = Signup::withTrashed()->where('email', '=', \Input::get('newsletter_unsubscribe_email'))->first(); if ($signup->trashed()) { if (\Request::ajax()) { return \Response::JSON(array('message' => \Lang::get('laravel-newsletter-signup::copy.unsubscribe.already_unsubscribed')), 400); } $message = new MessageBag(); $message->add('newsletter_unsubscribe_email', \Lang::get('laravel-newsletter-signup::copy.unsubscribe.already_unsubscribed')); return \Redirect::to(\Input::get('from'))->withInput()->with('errors', $message); } $signup->delete(); $success = \Lang::get('laravel-newsletter-signup::copy.unsubscribe.success'); if (\Request::ajax()) { return \Response::JSON(array('message' => $success)); } return \Redirect::to(\Input::get('from'))->with('newsletter_unsubscribe_email_message', $success); }
/** * Display a listing of the resource. * * @return Response */ public function index() { $error = ''; /* $track = resi::select('resi.noresi','k.nama AS konsumen', 'ca.nama AS asal','ct.nama AS tujuan', 'b.tglberangkat',//'b.jamberangkat', 'b.tgltiba', 'b.nopolisi','ps.nama AS sopir','pk.nama AS kenek', 'u.name AS user', 'resi.status') ->leftJoin('konsumen as k','k.idkonsumen','=','resi.idkonsumen') ->leftJoin('berangkat as b','b.idberangkat','=','resi.idberangkat') ->leftJoin('cabang as ca','ca.idcabang','=','b.idasal') ->leftJoin('cabang as ct','ct.idcabang','=','b.idtujuan') ->leftJoin('pegawai as ps','ps.idpegawai','=','b.idsopir') ->leftJoin('pegawai as pk','pk.idpegawai','=','b.idkenek') ->leftJoin('users as u','u.id','=','resi.user') ->where('resi.noresi','=',Request::get('id'))->get(); //*/ $resi = resi::find(Request::get('id')); if (!$resi) { $error = new MessageBag(); $error->add('notfound', 'Maaf resi dengan nomer ' . Request::get('id') . ' tidak ditemukan'); return view('master')->with('track', true)->withErrors($error); } else { $data = resi::select('resi.idberangkat', 'resi.idrute', 'resi.noresi', 'tk.nama as prspengirim', 'tk.cp as cppengirim', 'rk.nama as prspenerima', 'rk.cp as cppenerima', 'tc.nama as cabangasal', 'rc.nama as cabangtujuan', 'berangkat.nopolisi', 'berangkat.supir1', 'berangkat.supir2', 'rute.tglbrkt', 'rute.tgltiba')->leftJoin('konsumen AS tk', 'tk.idkonsumen', '=', 'resi.idkonsumen')->leftJoin('konsumen AS rk', 'rk.idkonsumen', '=', 'resi.idpenerima')->leftJoin('rute', function ($join) { $join->on('rute.sjt', '=', 'resi.idberangkat'); $join->on('rute.id', '=', 'resi.idrute'); })->leftJoin('cabang AS tc', 'tc.idcabang', '=', 'rute.kotamuat')->leftJoin('cabang AS rc', 'rc.idcabang', '=', 'rute.kotabongkar')->leftJoin('berangkat', 'berangkat.idberangkat', '=', 'rute.sjt')->where('resi.noresi', Request::get('id'))->first(); $posisi = posisiarmada::where('sjt', $data->idberangkat)->where('id', $data->idrute)->get(); return view('master')->with('track', true)->with('data', $data)->with('posisi', $posisi); } //('errorstracking',$error); }
/** * Account sign up form processing for register2 page * * @return Redirect */ public function postRegister2() { // Declare the rules for the form validation $rules = array('first_name' => 'required|min:3', 'last_name' => 'required|min:3', 'email' => 'required|email|unique:users', 'email_confirm' => 'required|email|same:email', 'password' => 'required|between:3,32', 'password_confirm' => 'required|same:password', 'terms' => 'accepted'); // Create a new validator instance from our validation rules $validator = Validator::make(Input::all(), $rules); // If validation fails, we'll exit the operation now. if ($validator->fails()) { // Ooops.. something went wrong return Redirect::back()->withInput()->withErrors($validator); } try { // Register the user $user = Sentinel::registerAndActivate(array('first_name' => Input::get('first_name'), 'last_name' => Input::get('last_name'), 'email' => Input::get('email'), 'password' => Input::get('password'))); //add user to 'User' group $role = Sentinel::findRoleById(2); $role->users()->attach($user); // Log the user in Sentinel::login($user, false); // Redirect to the home page with success menu return Redirect::route("dashboard")->with('success', Lang::get('auth/message.signup.success')); } catch (UserExistsException $e) { $this->messageBag->add('email', Lang::get('auth/message.account_already_exists')); } // Ooops.. something went wrong return Redirect::back()->withInput()->withErrors($this->messageBag); }
public function getAuthState() { $state = new JobAuthState(); $state->authMechanism = self::AUTH_MECHANISM; if (!Input::has('access_token')) { return $state; } $ownerId = $this->authServer->getResourceOwnerId(); $type = $this->authServer->getResourceOwnerType(); if ($type == 'user') { //oAuth token belongs to a user $user = User::find($ownerId); $actAs = $user->id; if (Input::has('act_as')) { if ($user->hasRole(UserRole::ACTOR_ROLE)) { $actAs = Input::get('act_as'); } else { $bag = new MessageBag(); $bag->add('authorisation', 'The current user cannot act as another user'); throw new AuthorisationException($bag); } } $state->userId = $user->id; $state->rememberMe = false; $state->actingUserId = $actAs; } else { //oAuth token belongs to a client //$client = OAuthClient::find($ownerId); //There is no user context and act_as shouldn't be needed as clients can use //access tokens if they want to execute as a user } return $state; }
public function validate() { $messageBag = new MessageBag(); if (!$this->relation_table || !\Schema::hasTable($this->relation_table)) { $messageBag->add($this->name, 'Invalid relation table on ' . $this->name); } return $messageBag->isEmpty() ? true : $messageBag; }
public function notRemember(BaseCommand $command) { if ($command->getAuthState()->rememberMe == true) { $bag = new MessageBag(); $bag->add('authorisation', 'This action cannot be performed using a `remembered` session'); throw new AuthorisationException($bag); } }
/** * Add a new message into the bag. * * @param string $message * @param string $key * @return \Codenest\Ahem\Notification */ public function addMessage($message, $key = null) { if ($key == null) { return $this->addMessages(array($message)); } $this->messages->add($key, $message); return $this; }