Checking Username Availability in Laravel - php

Is there a way to check if a username is already taken in laravel? I mean I want to check if a username is taken already without submitting the form that means checking the availability of the username while the user is typing. If there is what language should I use? And please cite examples. Thank you!

$count = User::where('userName', 'like', '%Lyka%')->count();
if($count > 0)
{
//username exists
}
else
{
//username doesn't exist
}
or you can validate in laravel validation itself
$rules = array('username' => 'required|unique:user');
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
$messages = $validator->messages()->first();
Session::put('msg',$messages);
return Redirect::back();
} else {
// username not exist
}
unique:user => unique from the table called user
username => is the column of the table user

A better approach would be to use laravel validation. Use ajax to send the input to laravel backend. And then somewhere in your controller.
$validator = Validator::make($request->all(), [
'username' => 'unique:users',
]);
And check if it fails
if ($validator->fails()) {
//do whatever you want to do at fail
//possible return appropriate json with error
}

Is there a way to check if a username is already taken in laravel?
Yes, try some PHP like the following:
$count = User::where('userName', '=', 'Lyka')->count();
if($count > 0)
{
//username exists
}
else
{
//username doesn't exist
}
If you want to check asynchronously you would have to write some Javascript and use AJAX to check while the user is filling out the form.
If there is what language should I use?
PHP obviously and Javascript.
Good luck.

Related

CodeIgniter - username and email existence check doesn't work

I'm trying to check whether or not an email or username exists in the database before inserting data into the database. For a reason I do not understand, despite using the email_exists and username_exists functions, when inserting the data, the database throws a field not unique error for username and email fields.
The username_exists and email_exists functions gets any usernames or emails where they match the username or email submitted by the form. The functions then return true if there is a username or email that exists, or false if the opposite. When both functions return false (i.e. username and email don't exist in the database) it inserts the form data into the database.
Any help would be great!
Controller Function
public function register(){
if($this->session->userdata('loggedIn') == TRUE){
$this->session->set_flashdata('error_msg', 'please log out to access this page ');
echo 'Please log out to access this page!...';
sleep(2);
redirect('index.php/user/dashboard');
}
$data['session_data'] = array(
'userID' => $this->session->userdata('userID'),
'loggedIn' => $this->session->userdata('loggedID')
);
$this->load->view('navigation');
$this->load->view('register', $data);
echo 'registration page - ';
if($this->input->post('register')){
$this->form_validation->set_rules('username', 'username', 'required');
$this->form_validation->set_rules('email', 'email', 'required|valid_email');
$this->form_validation->set_rules('password', 'password', 'required');
$user_details = array(
'username' => strip_tags($this->input->post('username')),
'email' => strip_tags($this->input->post('email')),
'password' => strip_tags($this->input->post('password'))
);
if($this->form_validation->run() == true){
$username_exists = $this->user_model->username_exists($user_details[0]);
$email_exists = $this->user_model->email_exists($user_details[1]);
if($username_exists == false && $email_exists == false) {
$this->user_model->add_user_account($user_details);
echo 'user added successfully: '. $user_details[0];
$this->session->set_flashdata('success_msg', 'SUCCESSFULLY ADDED USER, username and email do not already exist!... ');
sleep(2);
redirect('index.php/user/login');
} else {
echo 'username or email already exists! try again!...';
$this->session->set_flashdata('error_msg', 'ERROR OCCURRED - username or email exists!...');
sleep(2);
redirect('index.php/user/register');
}
} else {
echo 'error occured, try again!...';
$this->session->set_flashdata('error_msg', 'ERROR OCCURRED- something didn\'t work');
sleep(2);
redirect('index.php/user/register');
}
}
}
Model Functions
public function add_user_account($user_details){
$this->db->insert('user_account', $user_details);
}
public function username_exists($username){
$this->db->select('username');
$this->db->from('user_account');
$this->db->where('username', $username);
$query = $this->db->get();
if($query->num_rows() > 0){
return true;
} else {
return false;
}
}
public function email_exists($email){
$this->db->select('email');
$this->db->from('user_account');
$this->db->where('email', $email);
$query = $this->db->get();
if($query->num_rows() > 0){
return true;
} else {
return false;
}
}
$user_details[0] doesn't reference anything as you have non-numerical keys for the user_details array. I assume you mean to access the key username thus you should do $user_details['username'].
Like so:
$username_exists = $this->user_model->username_exists($user_details['username']);
$email_exists = $this->user_model->email_exists($user_details['email']);
To be honest I'm surprised this isn't giving you notice errors.
Further, you could easily make your username/email exists functions into a callback or simply use the is_unique feature of the form_validation library.
Also I'm pretty sure that you can apply strip_tags as a form_validation rule and it will remove the tags in the post variables.
Well to address your question via a means of simplification, you can use is_unique[table.field] as a validation rule.
That way you do not need to write any model methods for checking that your username or email is unique.
So in your form validation rules you can alter your username and email rules to include the is_unique rule.
$this->form_validation->set_rules('username', 'Username', 'required|is_unique[user_account.username]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[user_account.email]');
Note: The 2nd Field is the Form Label and can be anything. In this case I uppercased it. The 1st field IS case sensitive.
As to why your existing code isn't working...
Try getting friendly using var_dump(); or print_r();
i.e.
$username_exists = $this->user_model->username_exists($user_details[0]);
$email_exists = $this->user_model->email_exists($user_details[1]);
// Debug these two and see what they are...
var_dump($username_exists);
var_dump($email_exists);
Now seeing you are using an associative array in setting up
$user_details = array(
'username' => strip_tags($this->input->post('username')),
'email' => strip_tags($this->input->post('email')),
'password' => strip_tags($this->input->post('password'))
);
And then referencing them like
$username_exists = $this->user_model->username_exists($user_details[0]);
Using the above var_dump's should give you an "Aha!!!" moment.
When in doubt var_dump();

getting the query from database - Codeigniter

I wanted to check whether the username exists in the database,
but Codeigniter is throwing an
Error: Can't use method return value in write context.
The code is as follows:
public function check_username_exists($username){
$query = $this->db->get_where('users', array('username' => $username));
if(empty($query->row_array())){
return true;
}else{
return false;
}
}
$result = $query->row_array();
if(empty($result)){
return true;
}else{
return false;
}
try using below code
public function check_username_exists($username){
$query = $this->db->get_where('users', array('username' => $username));
if($query->num_rows() > 0){
return true;
}else{
return false;
}
}
It looks like you are trying to validate a form for user registration. If this is the case, then you would be far better off using the built-in form_validation library (https://codeigniter.com/user_guide/libraries/form_validation.html). There is already a built in method that would help you make sure you have unique records (such as the username). So basically, once the form_validation library is loaded, you would need to set the rules for validation. Once rules are set, you can call the run() method, which will produce a bool true/false whether it passes validation or not.
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', "trim|required|is_unique[users.username]");
if($this->form_validation->run() === true) {
//Do something when posted form is validated
} else {
// There were errors or this is the first time
if(validation_errors())
$data['error_message'] = validation_errors();
}
You should use the form validation library to validate any (and usually all) of your forms throughout your application
Hope that helps
First Understand the Error: Can't use method return value in write context.
empty() needs to access the value by reference (in order to check whether that reference points to something that exists).
However, the real problem you have is that you use empty() at all, mistakenly believing that "empty" value is any different from "false".
Empty is just an alias for !isset($thing) || !$thing. When the thing you're checking always exists (in PHP results of function calls always exist), the empty() function is nothing but a negation operator.
Not Coming to your problem, As Scott Miller suggest you can use CodeIgniter validation. And if you want a little advance solution then you can put your validation in the config folder with creating form_validation.php for more detail visit CodeIgniter documentation for validation.
$config = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required|is_unique[users.username]'
)
);
And If you want to do it with the query then here is the query:
public function check_username_exists($username){
$query = $this->db->get_where('users', array('username' => $username));
if ($query->num_rows() > 0){
return true;
}
else{
return false;
}
}
You can use num_rows to get the username exist or not.

CakePHP 3 - Compare passwords

I have two field "password" (This field is in the database) and confirm_password (This field is not in the database)
Well, I need to compare if password == confirm_password.. but I'm not knowing create a custom validation to "confirm_password"... Would need to have this field in the database?
How do I do?
Generally you can access all data in a custom validation rule via the $context argument, where it's stored in the data key, ie $context['data']['confirm_password'], which you could then compare to the current fields value.
$validator->add('password', 'passwordsEqual', [
'rule' => function ($value, $context) {
return
isset($context['data']['confirm_password']) &&
$context['data']['confirm_password'] === $value;
}
]);
That being said, recently a compareWith validation rule was introduced which does exactly that.
https://github.com/cakephp/cakephp/pull/5813
$validator->add('password', [
'compare' => [
'rule' => ['compareWith', 'confirm_password']
]
]);
Now there has a method call sameAs in validator class, for version 3.2 or grater.
$validator -> sameAs('password_match','password','Passwords not equal.');
see API
I know it's late answer but will help to other.
// Your password hash value (get from database )
$hash = '$2y$10$MC84b2abTpj3TgHbpcTh2OYW5sb2j7YHg.Rj/DWiUBKYRJ5./NaRi';
$plain_text = '123456'; // get from form and do not make hash. just use what user entred.
if (password_verify($plain_text, $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
OR
$hasher = new DefaultPasswordHasher();
$check = $hasher->check($plain_text,$hash); // it will return true/false

How to compare Laravel's hash password using a custom login form?

Can you help me with this? I am building my own login form using Laravel. But I have a problem because I stored my password using Hash method and in my login form I used hash method again to compare. But I found out that the hash value is always changing.
Here's my code in routes:
Route::post('/admin_handle_login', function()
{
$rules = array(
'admin_username' => 'required',
'admin_password' => 'required'
);
$validate_admin_login = Validator::make(Input::all(), $rules);
if($validate_admin_login->fails()) {
$messages = $validate_admin_login->messages();
Session::flash('warning_notification','Error: Incomplete details!');
return Redirect::to('/flaxadmin')
->withErrors($messages)
->withInput(Input::except('admin_password'));
} else {
$d = array(
Input::get('admin_username'), Hash::make(Input::get('admin_password'))
);
$validate_admin = DB::table('administrators')
->select('username')
->where('username', Input::get('admin_username'))
->where('password', Hash::check('password', Input::get('admin_password')))
->count();
fp($d);
fp($validate_admin);
}
});
The result is
Array
(
[0] => admin002
[1] => $2y$10$RTwKHN9W1/unu1ZhYlNjauApJjjoNTBnE6td/AZ5jWgZEdqVav0um
)
0
In my database the password of admin002 is
$2y$10$47sSXLzh/YXN6Rf2fmljYO7lZaxfhXVSUTp5bssR2gYQ6Nw9luUH2
Is my code wrong? Or are there any proper way to do this? I am a begiiner in Laravel..
First, you cannot do it this way. Assuming username is unique, you should do:
$validate_admin = DB::table('administrators')
->select('username')
->where('username', Input::get('admin_username'))
->first();
if ($validate_admin && Hash::check(Input::get('admin_password'), $validate_admin->password)) {
// here you know data is valid
}
However you should think about rather using built-in methods than coding it yourself. You have Auth::attempt or Auth::validate if you want to login/check only user with password so there's really no need to code it yourself.
Here you're checking the string 'password' with the hashed version of the input password.
So try fetching the user by their username and if you've a result you can compare the hashed version of the password, stored in the database, with the input password. Like so:
$user = DB::table('administrators')
->select('username', 'password')
->where('username', Input::get('admin_username');
if($user->count()) {
$user = $user->first();
if(Hash::check(Input::get('admin_password'), $user->password)) {
//User has provided valid credentials :)
}
}
A slight improvement to marcin-nabiaƂek's answer, you can now use PHP's password_verify to achieve the same
$user = App\User::where('email', $request->email)->first();
if($user && password_verify($request->password, $user->password)) {
// authenticated user,
// do something...
}
This is useful code 100% laravel 6/7/8.
if ($data = AddEmployee::where('name', $request->name)-first()) {
$pass = Hash::check($request->password, $data->password);
if ($pass) {
echo "sucess";
} else {
echo "Password Not Valid";
}
} else {
echo "Username Not Valid" . "<br>";
}

Passing Data to view in a Redirect request to prevent double submission

I am trying to prevent double submission through the back button in a simple voting application
I was doing this before. After voting it returns this view
return View::make('votes.votesresults')->with('candidates',$candidates)->with('count',$count);
This passes two variables to votesresult view but unfortunately if someone clicks the back button they can resubmit their votes. I looked around and came across the PRG pattern. Am supposed to use a redirect to prevent this. So i tried this
return Redirect::route('votes.votesresults')->with('candidates',$candidates)->with('count',$count);
Here are my controllers
public function votesuccess()
{
$rules = array(
'name' => 'required'
);
$validator = Validator::make(Input::all(),$rules);
if ($validator->fails()) {
return Redirect::to('votes/index')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// store
$vote = new Vote;
$candidates = Candidate::all();
$candidate_id =Input::get('name');
$candidate = Candidate::find($candidate_id);
$vote = $candidate->votes()->save($vote);
//$count = DB::table('votes')->where('candidate_id','=','$candidate_id')->count();
$count = DB::table('votes')->count();
// redirect
Session::flash('message', 'Successfully Cast your vote!');
//return View::make('votes.voteresults')->with('candidates', $candidates)->with('count',$count);
return Redirect::route('voteresults')->with('candidates', $candidates)->with('count',$count);
}
}
public function voteresult()
{
$candidates = Candidate::all();
return View::make('votes.voteresults');
}
My routes are like this
Route::post('votesuccess', array('as' => 'votesuccess', 'uses'=>'VoteController#votesuccess'));
Route::get('voteresults', array('as' => 'voteresults', 'uses'=>'VoteController#voteresult'));
This does not work because it returns undefined variable: candidates. My results view requires these variables. So how do I implement the PRG pattern correctly such that I prevent double submission while being able to pass data to my view
You are redirecting to the route named voteresults, which is handled by the voteresult function and not the votesuccess function.
In your votesuccess function, you should load the view and include the candidates variable in that view. You can access the candidates variable stored in the session by using Session::get('candidates').
It would help to see you voter results view to see what's going on there, and where/how you've put in logic to avoid duplicate submission. Are you concerned about accidental re-submissions, or just multiple submissions from the same user? If the latter, then you would need to build in some logic that limits a user to only 1 vote. You could do this by check if the user has a related vote.
if ( ! $candidate->votes() ) {
// no votes exist, proceed with storing vote
}
Below is you controller refactored a bit:
public function votesuccess()
{
$rules = array(
'name' => 'required'
);
$validator = Validator::make(Input::all(),$rules);
if ($validator->fails()) {
return Redirect::back('votes/index')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// store
$candidate = Candidate::find(Input::get('name'));
$vote = $candidate->votes()->save(new Vote);
// redirect
Session::flash('message', 'Successfully Cast your vote!');
return Redirect::route('voteresults');
}
}
public function voteresult()
{
$candidates = Candidate::all();
$count = DB::table('votes')->count();
return View::make('votes.voteresults', compact('candidates', 'count'));
}

Categories