Laravel validation - php

I have problem with Laravel validation when validation fails it also call block of code where it should be successful...
I am trying to check for some user id if his admin_id field equal with user which is currently logged.
Here is code:
$auth = Auth::user()->id;
$inputs = array(
'id' => Input::get('id')
);
$rules = array(
'id' => "required|exists:users,id,admin_id,$auth"
);
$validate = Validator::make($inputs, $rules);
if ($validate->fails()) {
return $validate->messages()->all();
} else {
return 'succes';
}

Try doing this:
$rules = array(
'id' => "required|exists:users,id,admin_id," . $auth
);

You can do this without validation.
$auth = Auth::user()->id;
$input = Input::get('id');
if($auth != $input){
return 'your custom error message';
}else{
return 'success';
}

Related

Undefined property: App\Http\Controllers\PostController::$p

my controller look like
public function react(Request $request){
//echo "hi";
//return;
//return response()->json($request);
$this->validate($request, [
'postid' => 'required',
'react' => 'required'
]);
$reaction = Reaction::firstOrNew([
'post_id'=>$request->postid,
'user_id'=> Auth::id()
]);
$reaction->user_id = Auth::id();
$reaction->type = $request->react;
$reactType = "";
if ($request->react === "l"){$reactType = "liked";}
else if ($request->react === "d"){$reactType = "disliked";}
else if ($request->react === "h"){$reactType = "loved";}
else if ($request->react === "s"){$reactType = "Smiled";}
else{}
$post = Post::find($request->postid);
$postuser = $post->user->name;
if($post->reactions()->save($reaction)){
$data['message'] = Auth::user()->name.' '.$reactType. ' a Post from' . $postuser;
$data['type'] = 'reaction';
**$this->p->trigger('user-'.$post->user_id, 'new-post', $data);**
return response()->json([
'success' => true,
'message' => 'Reacted'
]);
}
else{
return response()->json([
'success' => false,
'message' => 'Error'
]);
}
AND I AM UNABLE TO LINK WITH PUSHER CHANNEL
But I keep getting an error
Undefined property: App\Http\Controllers\MyController::$p
What am I doing wrong? Would highly appreciate any possible help!
property $this->p (p) , You have not set the value
$this->p = Value ;
After setting, you can use the information.
$this->p->trigger('user-'.$post->user_id, 'new-post', $data);
In the code written above, $this->p has an null value
$this->null->trigger('user-'.$post->user_id, 'new-post', $data);
In fact, this is how you use it

Laravel Validation is validating data but then redirecting to the same page with the inputs without executing the following code

Here is my code for validation.
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email|unique:users',
'phone' => 'required|unique:users',
'user_name' => 'required|unique:users',
'operator_name' => 'required|max:255',
'operator_nid' => 'required|numeric|unique:operators',
'operator_password' => 'required',
'operator_gender' => 'required',
'operator_birthday' => 'required',
]);
if ($validator->fails()) {
return redirect('operator/create')
->withErrors($validator)
->withInput();
}
$user = new User;
$user->name = $request->operator_name;
$user->email = $request->email;
$user->phone = $request->phone;
$user->user_name = $request->user_name;
$user->password = bcrypt($request->password);
$user->type = 3;
$user->save();
$operator = new Operator;
$operator->operator_name = $request->operator_name;
$operator->operator_email = $request->email;
$operator->operator_phone = $request->phone;
$operator->operator_nid = $request->operator_nid;
$operator->operator_user_name = $request->user_name;
$operator->user_id = $user->id;
$operator->type = 3;
$operator->operator_gender = $request->operator_gender;
$operator->operator_birthday = $request->operator_birthday;
$operator->operator_occupation = $request->operator_occupation;
$operator->operator_facebook = $request->operator_facebook;
$operator->operator_twitter = $request->operator_twitter;
$operator->operator_gplus = $request->operator_gplus;
$operator->operator_address = $request->operator_address;
if ($request->hasfile('operator_pro_pic')){
$image = $request->file('operator_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/operator/' . $filename);
Image::make($image)->resize(950, 700)->save($location);
$operator->operator_pro_pic = $filename;
}
$operator->save();
return $user;
}
I am trying to create an operator and a user at the same time. email, phone and user_name should be unique in the user's table and other data will be validate from the operators table. Validation is working as it is giving me the errors but after validating it's not going further. So my code after the validation is not executing. What is the possible reason for this?
You can use -
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator);
}
The better way will be to create a request file by using
php artisan make:request requestName
define all the validation in there. In this case if your validation fails the application will return back with error and old-inputs without reaching to the controller.

Password automatically changed on DB while update personal details usin cake PHP

if i update any of this personal details filed then i click on save it. its save the new data and change my login password also to random value
public function update_personal_details() {
$this->layout = null ;
$this->autoRender = false;
$response = array('success' => true);
if ($this->request->isPost()) {
if($this->User->exists($this->Auth->user('id'))) {
try {
$this->User->read(null, $this->Auth->user('id'));
$this->User->set('first_name',$this->request->data["first_name"]);
$this->User->set('last_name',$this->request->data["last_name"]);
$this->User->set('mobile',$this->request->data["mobile"]);
$this->User->set('city',$this->request->data["city"]);
$this->User->save();
} catch (exception $ex) {
$response['success'] = false;
}
}
}
return json_encode($response);
}
To make sure that cakePHP only updates the wanted cols you can pass the data and a field list on the save command:
Model::save(array $data = null, boolean $validate = true, array $fieldList = array())
Just have a look at Cookbook Save your Data
For you this should work:
$data = array();
$data['first_name'] = $this->request->data["first_name"]);
$data['last_name'] = $this->request->data["last_name"]);
$data['mobile'] = $this->request->data["mobile"]);
$data['city'] = $this->request->data["city"]);
$this->User->save(array('User' => $data), true, array('first_name', 'last_name', 'mobile', 'city'));
Hope that helps

Variable button label

I got a form for the registration of a user and use it as an edit-user-form, too.
Now I want to make this form more vabiable. That means in my case: I want to have a specific button label for the different actions.
If the form is called via RegisterAction, the label should be "Register" and if it's called via EditAction, it shall be "Update user". I tried some things but now I ran out of ideas.
Here is my code:
CustomerController.php
...
public function registerAction(){
$form = new Application_Form_Register();
$request = $this->_request->getParams();
if(isset($request['registerbtn']) && ($form->isValid($request) )){
$customerModel = new Application_Model_Customer();
$customerArr = $customerModel->setCustomer($request,true);
$this->redirect('/customer/detail/id/'.$customerArr);
}
else{
$this->view->form = $form;
$this->view->button = "Register"; //TEST
}
}
public function editAction(){
$request = $this->_request->getParams();
if(isset($request['id']) && !empty($request['id'])){
$form = new Application_Form_Register();
$form->addElement('hidden', 'id', array(
'required' => true,
'value' => $request['id'],
'validators' => array(
$digits = new Zend_Validate_Digits()
)
));
if(isset($request['registerbtn']) && ($form->isValid($request) )){
$customerModel = new Application_Model_Customer();
$id = $customerModel->setCustomer($request,false);
$this->redirect('/customer/detail/id/'.$id);
}else{
$modelResult = new Application_Model_Customer();
$customer = $modelResult->getCustomer($request['id']);
$cArr = $customer->toArray();
$form->populate($cArr);
$this->view->form = $form;
$this->view->button = "Update user"; //TEST
}
}else{
$this->redirect('/');
}
}
...
The views
// register.phtml - begin
<h2>Registration</h2>
<?php
$this->headTitle('Registration');
$button = $this->button; //TEST
$this->form->button = $button; //TEST
echo $this->form;
echo $this->error;?>
// register.phtml - end
// edit.phtml - begin
<?php
echo $this->headline;
$this->headTitle('Update user');
$button = $this->button; //TEST
$this->form->button = $button; //TEST
echo $this->form;
?>
// edit.phtml - end
And the form
//
...
$this->addElement('submit', 'registerbtn', array(
'ignore' => true,
'label' => $button, //TEST
'decorators' => $this->buttonDecorators,
));
...
I fear that this is totally wrong but I don't know how to do it right.
Try something like
if ($cas1)
$form->getElement('submit')->setLabel('cas1');
else
$form->getElement('submit')->setLabel('cas2');

CakePHP Login with both username and email using Auth Component

I want the auth component to allow user to login entrying either username or email.
In my users table, both fields - userName and userEmail are unique.
At time of registration, the password is generated like:
sha1($username.$password);
The problem is that user is not able to login using email.
App Controller
var $components = array('Auth');
public function beforeFilter(){
if(isset($this->params['prefix']) && $this->params['prefix'] == 'webadmin') {
$this->Auth->userModel = 'Admin';
$this->Auth->logoutRedirect = $this->Auth->loginAction = array('prefix' => 'webadmin', 'controller' => 'login', 'action' => 'index');
$this->Auth->loginError = 'Invalid Username/Password Combination!';
$this->Auth->authError = 'Please login to proceed further!';
$this->Auth->flashElement = "auth.front.message";
$this->Auth->loginRedirect = array('prefix'=>'webadmin', 'controller'=>'dashboard', 'action'=>'index');
}
else{
$this->layout="front";
//$this->Auth->autoRedirect = false;
// $this->Auth->logoutRedirect = $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
// $this->Auth->loginRedirect = array('controller'=>'blogs', 'action'=>'index');
$this->Auth->fields = array(
'username' => 'userName',
'password' => 'password'
);
$this->Auth->userScope = array('User.status'=>1);
$this->Auth->loginError = "The username/email and password you entered doesn't match our records.";
$this->Auth->authError = 'Please login to view this page!';
$this->Auth->flashElement = "auth.front.message";
$this->Auth->loginRedirect = array('controller'=>'profiles', 'action'=>'index');
}
Users Controller: the login function goes like:
if(!empty($this->data))
{
// Try to login with Email
if (!empty($this->Auth->data)) {
// save username entered in the login form
$username = $this->Auth->data['User']['userName'];
// find a user by e-mail
$find_by_email = $this->User->find('first', array(
'conditions' => array('userEmail' => $this->Auth->data['User']['userName']),
'fields' => 'userName'));
// found
if (!empty($find_by_email))
{
$this->Auth->data['User']['userName'] = $find_by_email['User']['userName'];
$this->data['User']['password']=$this->Auth->data['User']['password'];
if (!$this->Auth->login($this->data)) {
// login failed
// bring back the username entered in the login form
$this->Auth->data['User']['username'] = $username;
} else {
$this->Session->delete('Message.auth');
// redirect
if ($this->Auth->autoRedirect) {
$this->redirect($this->Auth->redirect(), null, true);
}
}
}
}
}
Auth.php:(I have made some changes here in the way password is generated as I am using the cakephp session to auto-login to SMF forum.)
function login($data = null) {
$data['User.password'] = sha1(strtolower($data['User.userName']) . $_POST['data']['User']['password']);
$this->__setDefaults();
$this->_loggedIn = false;
if (empty($data)) {
$data = $this->data;
}
if ($user = $this->identify($data)) {
$this->Session->write($this->sessionKey, $user);
$this->_loggedIn = true;
}
return $this->_loggedIn;
}
I took help from this link, but I am not getting username in $data['User.userName'] in auth.php, I getting email here, so the password goes wrong and results in login failure.
Please help.
You have error in the conditions, it should be:
'conditions' => array('userEmail' => $this->Auth->data['User']['email']),
You are checking the username .
The only way I could make it work is by modifying auth.php in cake.
App Controller
I added this to the code in before filter:
$this->Auth->fields = array(
'username' => 'userName',
'email'=>'userEmail',
'password' => 'password'
);
Users Controller I removed all the extra code.
Auth.php
I made changes to the identify function to check email after encrypting the password in //the way I wanted.
function identify($user = null, $conditions = null) {
if ($conditions === false) {
$conditions = array();
} elseif (is_array($conditions)) {
$conditions = array_merge((array)$this->userScope, $conditions);
} else {
$conditions = $this->userScope;
}
$model =& $this->getModel();
if (empty($user)) {
$user = $this->user();
if (empty($user)) {
return null;
}
} elseif (is_object($user) && is_a($user, 'Model')) {
if (!$user->exists()) {
return null;
}
$user = $user->read();
$user = $user[$model->alias];
} elseif (is_array($user) && isset($user[$model->alias])) {
$user = $user[$model->alias];
}
if (is_array($user) && (isset($user[$this->fields['username']]) || isset($user[$model->alias . '.' . $this->fields['username']]))) {
if (isset($user[$this->fields['username']]) && !empty($user[$this->fields['username']]) && !empty($user[$this->fields['password']])) {
if (trim($user[$this->fields['username']]) == '=' || trim($user[$this->fields['password']]) == '=') {
return false;
}
$find = array(
$model->alias.'.'.$this->fields['username'] => $user[$this->fields['username']],
$model->alias.'.'.$this->fields['password'] => $user[$this->fields['password']]
);
} elseif (isset($user[$model->alias . '.' . $this->fields['username']]) && !empty($user[$model->alias . '.' . $this->fields['username']])) {
if (trim($user[$model->alias . '.' . $this->fields['username']]) == '=' || trim($user[$model->alias . '.' . $this->fields['password']]) == '=') {
return false;
}
// my code starts
$user['User.userEmail']=$user['User.userName'];
//find username using email
$find_by_email= $model->find('first', array(
'fields' => array('User.userName','User.realpass'),
'conditions' => array($model->alias.'.'.$this->fields['email'] => $user[$model->alias . '.' . $this->fields['email']]),
'recursive' => 0
));
if(!empty($find_by_email))
{
$uname=strtolower($find_by_email['User']['userName']);
$pwd=$user[$model->alias . '.' . $this->fields['password']];
}
else
{
$uname=strtolower($user[$model->alias . '.' . $this->fields['username']]);
$pwd=$user[$model->alias . '.' . $this->fields['password']];
}
$thepassword = sha1($uname.$pwd); // encrypt password
// find user where username or email equals to the username passed
$find = array(
'OR' => array($model->alias.'.'.$this->fields['username'] => $user[$model->alias . '.' . $this->fields['username']], $model->alias.'.'.$this->fields['email'] => $user[$model->alias . '.' . $this->fields['username']]),
$model->alias.'.'.$this->fields['password'] => $thepassword
);
} else {
return false;
}
$cond=array_merge($find, $conditions);
$data = $model->find('first', array(
'conditions' => $cond,
'recursive' => 0
));
// my code ends here
if (empty($data) || empty($data[$model->alias])) {
return null;
}
} elseif (!empty($user) && is_string($user)) {
$data = $model->find('first', array(
'conditions' => array_merge(array($model->escapeField() => $user), $conditions),
));
if (empty($data) || empty($data[$model->alias])) {
return null;
}
}
if (!empty($data)) {
if (!empty($data[$model->alias][$this->fields['password']])) {
unset($data[$model->alias][$this->fields['password']]);
}
return $data[$model->alias];
}
return null;
}
Lastly, I commented the password encrypt code to return the simple password so that I can encrypt it the wat I needed in the above function.
function password($password) {
//return Security::hash($password, null, true);
return $password;
}

Categories