Hashing laravel 4.5 user password - php

I try to give users ability to change their password in profile page but when they change the password, password will not be hashed.
This is my update function in usercontroller:
public function update(Request $request, $id)
{
$user = User::find($id);
$this->validate($request, array(
'name' => 'required|string|max:255',
'email' => [
'required','nullable','string','email','max:255',
Rule::unique('users')->ignore($user->id),
],
'gender' => 'required|string',
'password' => 'nullable|string|min:6|confirmed',
));
$user = User::find($id);
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->gender = $request->input('gender');
$user->password = $request->input('password');
$user->save();
Session::flash('success', 'Your information was successfully updated.');
return redirect()->route('users.list');
}

I solved the issue with using Trim. here is the code for those who need it:
if (trim(Input::get('password')) != '') {
$user->password = Hash::make(trim(Input::get('password')));
}

Related

Return JSON response in Laravel for duplicate email login via API

This is my API register method for taking new user registration into the Database.
public function register(Request $request)
{
$user = new User();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = Hash::make($request->input('password'));
if($user->save()){
response (['result' => true]);
}
return response(['result' => false,]);
}
Now when I register from the same email Id, I am getting errors like below
Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'pkyadav#gmail.com' for key 'users_email_unique' (SQL: insert into `users` (`name`, `email`, `password`, `updated_at`, `created_at`) values (Pramod, pkyadav#gmail.com, y$WJJrNjB8K/jGSXpPagVjSujZcifKXrzs3gnvPcjSK3W1c.IekaBna, 2021-12-16 07:46:56, 2021-12-16 07:46:56))
I want to get a false result response on a duplicate email registration
You can add Validation using Exists:
Example: $user->where('email',$request->input('email'))->exists()
See the below code:
public function register(Request $request)
{
$user = new User();
if(!$user->where('email',$request->input('email'))->exists()){
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = Hash::make($request->input('password'));
if($user->save()){
return response(['result' => true]);
}else{
return response(['result' => false]);
}
}
return response(['result' => false,]);
}
You can use Laravel validation:
public function register(Request $request)
{
$validated = $request->validate([
'email' => 'required|unique:users',
]);
if($validation->fails()){
return response()->json($validation->errors());
}
$user = new User();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = Hash::make($request->input('password'));
if($user->save()){
return response (['result' => true]);
}
return response(['result' => false,]);
}
You can be use Form Request.
https://laravel.com/docs/8.x/validation#form-request-validation
or you can use the following
public function register(Request $request){
$data = $request->validate([
'email' => 'required|email|unique:users',
'name' => 'required|string',
'password' => 'required|string'
]);
$data['password'] = bcrypt($data['password']);
try {
User::create($data);
return response()->json([
'message' => __('User created'),
'result' => true
]);
}catch (\Exception $exception){
return response()->json([
'message' => $exception->getMessage(),
'result' => false
]);
}
}

Creating default object from empty value in Laravel 6.2

I want to Update this data in database.
error :
ErrorException
Creating default object from empty value
i get error in this line :
$user->name = $request->name;
My Controller code is :
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required|max:255',
'mobile' => 'required|numeric|regex:/(0)[0-9]/|not_regex:/[a-z]/|digits:11',
'national_code' => 'required|numeric|regex:/(0)[0-9]/|not_regex:/[a-z]/|digits:10',
'avatar' => 'required|mimes:jpg,jpeg,png',
]);
$id = (int)$id;
$user = User::findOrFail($id);
$user->name = $request->name;
$user->mobile = $request->mobile;
$user->national_code = $request->national_code;
$user->province = $request->province;
$user->city = $request->city;
$user->address = $request->address;
$user->postcode = $request->postcode;
$user->active = $request->active;
$user->avatar = $request->avatar;
if(! is_null($request->password)) {
$request->validate([
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
$user->password = $request->password;
}
$user->active = $request->active ? 1 : 0;
if ($request->role_id) {
$user->syncRoles($request->role_id);
}
$user->save();
$notification = array(
'message' => 'Success !',
'alert-type' => 'success'
);
return redirect(route('management.users.index'))->with($notification);
}
Route :
Route::resource('users', 'UserController');
Thank you
Try this:
$user = User::find($id)
or this:
$user = User::where('id', $id)->first();
And check if in your User Model:
protected $fillable = [
'name','mobile', 'national_code', 'city', 'province', 'address',
'postcode', 'active', 'avatar',
];

Password should not be update if user not give any value in password field laravel 5.3

I am working on edit profile and i want that password should not be update if user not give any values in password field now if user not enters any value then password update automatically
Here is my method
{
$this->validate($request, [
'name' => 'required|max:255',
]);
$user = User::findOrFail($id);
$input = $request->all();
$user->fill([
'name' => $request->input('name'),
'password' => bcrypt($request->input('password')),
'def_timezone' => $request->input('def_timezone'),
'address_line_1' => $request->input('address_line_1'),
])->save();
session()->flash('msg',trans('successfully Updated.'));
}
Please Help to fix the issue Thanks
You can do this:
'password' => $request->password ? bcrypt($request->password) : $user->password,
Also, you can use update() method instead of fill() and save(). With this approach empty values will be ignored:
$user->update($request->all());
You must do something like this into your edit validation
'password' => 'min:6|max:50',
So the user cant send an empty password to your db:
If you want to check before you update the user password , it will be good to have another field into your view the Old_password so you can check if the user remember the old password ans os can change it to a new one .
here is my example my update function:
public function update(Request $request, $id)
{
$update_user = Validator::make($request->all(), [
'name' => 'min:2|max:35|string',
'surname' => 'min:2|max:35|string',
'email' => Sentinel::inRole('Admin')?'required|email|min:3|max:50|string':(Sentinel::check()?'required|email|min:3|max:50|string|unique:users,email,'.$id:'required|email|min:3|max:50|unique:users|string'),
'old_password' => 'min:6|max:50',
'new_password' => 'min:6|max:50',
]);
if ($update_user->fails()) {
return redirect()->back()
->withErrors($update_user)
->withInput();
}
$user = User::find($id);
if ($user) {
if(!empty($request->file('image'))){
$file = $request->file('image');
$destinationPath = public_path() . '/upload-client/profile_image';
$filename = str_random(6) . '_' . $file->getClientOriginalName();
$unwanted = array("\'", "+", "%");
$filename =str_replace($unwanted, "", $filename);
$uploadSuccess = $file->move($destinationPath, $filename);
$user->image_path=$filename;
}
if($request->name){
$user->name=$request->name;
}
if($request->email){
$user->email=$request->email;
}
if($request->old_password){
if (Hash::check($request->old_password, $user->password)){
$user->password=bcrypt($request->new_password);
}else{
Session::flash('message', 'Your old password is incorrect.');
Session::flash('status', 'error');
return redirect()->back()->withErrors(['old_password', 'your old password is incorrect']);
}
}
$user->update();
if ($request->role) {
$user->roles()->sync([$request->role]);
}
Session::flash('message', 'Success! User is updated successfully.');
Session::flash('status', 'success');
}
return redirect()->back();
}

Retry logic on model save - Laravel

User_code is generated and must be unique. What would be the easiest/cleanest way to do retry logic on this model save? I would like to verify the generated code first, and then if it's not found on the users table, create the user, if found, loop to retry. What would be the syntax for that? Thanks
public function create(array $data)
{
$user = User::create([
'user_name' => 'My user name',
'user_code' => bin2hex(openssl_random_pseudo_bytes(16))
]);
$user->save();
return $user;
}
Why don't you check the database when generating the code? That way, you only try to create once you got it right and the end user doesn't have to face an error that is not up to him/her.
do {
$code = bin2hex(openssl_random_pseudo_bytes(16));
$record = User::where('user_code', $code)->get();
} while(!empty($record));
$user = User::create([
'user_name' => 'My user name',
'user_code' => $code
]);
return $user;
You could avoid the retry:
public function create(Request $request)
{
$request->merge(['user_code' => bin2hex(openssl_random_pseudo_bytes(16))]);
$this->validate($request, [
'user_name' => 'required|unique:users',
'user_code' => 'required|unique:users',
]);
$user = new User;
$user->user_name = $request->user_name;
$user->user_code = $request->user_code;
$user->save();
return $user;
}
You should create a unique string from the beginning. Still go for validation, of course.
public function create(Request $request)
{
$user_code = bcrypt($request->user_name . openssl_random_pseudo_bytes(16));
$request->merge(['user_code' => $user_code]);
$this->validate($request, [
'user_name' => 'required|unique:users',
'user_code' => 'required|unique:users',
]);
$user = User::create($request);
return $user;
}
A save() is implied by create().

Laravel update password passes validation but doesn't update record

Hi I am using Laravel and I am using a couple of packages for user auth and roles which are Zizaco Confide and I want to update the users password firstly they should input there current password a new password and confirm the password and they should match. Now the validation works but the users password isn't updated in the database. My code is below:
public function updatePassword($id) {
$rules = array(
'now_password' => 'required',
'password' => 'min:5|confirmed|different:now_password',
'password_confirmation' => 'required_with:password|min:5'
);
//password update.
$now_password = Input::get('now_password');
$password = Input::get('password');
$passwordconf = Input::get('password_confirmation');
$validator = Validator::make(Input::only('now_password', 'password', 'password_confirmation'), $rules);
if ($validator->fails()) {
return Redirect::back()->withErrors($validator);
}
elseif (Hash::check($now_password, Auth::user()->password)) {
$user = User::find($id);
$user->password = Hash::make($password);
$user->save();
return Redirect::back()->with('success', true)->with('message','User updated.');
} else {
return Redirect::back()->withErrors('Password incorrect');
}
}
Any ideas why the users password is not isn't updated using this block of code
$user = User::find($id);
$user->password = Hash::make($password);
$user->save();
User Model
<?php
use Zizaco\Confide\ConfideUser;
use Zizaco\Confide\ConfideUserInterface;
use Zizaco\Entrust\HasRole;
class User extends Eloquent implements ConfideUserInterface
{
use SoftDeletingTrait;
use ConfideUser;
use HasRole;
protected $softDelete = true;
public function favourites()
{
return $this->hasMany('Favourite');
}
}
To check inputted password:
1.
$now_password = Input::get('now_password');
$user = DB::table('users')->where('name', Auth::user()->name)->first();
if(Hash::check($now_password, $user->password)){
//Your update here
}
2.
$now_password = Input::get('now_password');
if(Hash::check($now_password, Auth::user()->password)){
//Your update here
}
To check if they match and if the new password is different than old.
$rules = array(
'now_password' => 'required|min:8',
'password' => 'required|min:8|confirmed|different:now_password',
'password_confirmation' => 'required|min:8',
);
And edit your form to (or enter your names):
{{ Form::label('now_password', 'Old Password') }}
{{ Form::password('now_password')}}
{{ Form::label('password', 'New Password') }}
{{ Form::password('password')}}
{{ Form::label('password_confirmation', 'Confrim New Password') }}
{{ Form::password('password_confirmation')}}
Update
Ok, so you don't want to edit only passwords.
Edit your rules:
$rules = array(
'now_password' => 'required|min:5',
'password' => 'min:5|confirmed|different:now_password',
'password_confirmation' => 'required_with:password|min:5'
);
I think that current password should be required in every type of change. Other inputs imo shouldn't be required, because you don't know which data user want to edit.
You should also add to your rules something like:
'username' => alpha_num|unique:users,username
etc.. (for more see http://laravel.com/docs/4.2/validation#available-validation-rules)
If Validator pass, you should check which data user want to change (which inputs are not empty).
Something like:
if(!empty(Input::get('firstname'))){
$user->firstname = Input::get('firstname');
}
etc...with every input.
Try it like this:
public function updatePassword($id)
{
$user = User::findOrFail($id);
User::$rules['now_password'] = 'required';
// other rules here
$validator = Validator::make($data = Input::all(), User::rules('update', $id));
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
array_forget($data, 'password_confirmation');
array_forget($data, 'now_password');
$data['password'] = Hash::make($data['password']);
$user->update($data);
return Redirect::back()->with('success', true)->with('message','User updated.');
}
remember your password confirmation field name must be "password_confirmation" if you used first way...
if you used another name for password confirm field you can use second way.
$this->validate($request, [
'email' => 'required|unique:user|email|max:255',
'username' => 'required|max:20',
'password' => 'required|min:3|confirmed',
'password_confirmation' => 'required',
'gender' => 'required|in:m,f',
]);
$this->validate($request, [
'email' => 'required|unique:user|email|max:255',
'username' => 'required|max:20',
'password' => 'required|min:3',
'confirm_password' => 'same:password',
'gender' => 'required|in:m,f',
]);
public function change_password_post($id)
{
$rules = array(
'current' => 'required|string|min:8',
'new' => 'required|string|min:8',
'confirm' => 'required|same:new'
);
$validator = Validator::make(Input::only('current', 'new', 'confirm'), $rules);
if($validator->fails())
{
return Redirect::back()
->withErrors($validator);
}
else
{
$users = User::where('id', '=', $id)->first();
if (Hash::check(Input::get('current'), $users->password))
{
if(Input::get('new') == Input::get('confirm'))
{
$users->password =Hash::make(Input::get('new'));
$users->save();
$msg = array('msg' => 'Password changed Successfully');
return Redirect::back()
->withErrors($msg);
}
else
{
$msg = array('msg' => 'New password and Confirm password did not match');
return Redirect::back()
->withErrors($msg);
}
}
else
{
$msg = array('msg' => 'Current password is incorrect');
return Redirect::back()
->withErrors($msg);
}
}
}

Categories