Laravel sometimes validation rule not working - laravel

I'm trying to implement the sometimes validation rule into one of my projects (Laravel 5.6).
I have a profile page that a user can update their name and password, but i want to make it so that if the user doesnt enter a password, it wont update that field, which is what i thought the sometimes rule was.
The complete update method i am using in my controller is below.
If i leave the password field blank, then it returns a string or min error which it shouldn't be doing.
public function update()
{
$user = Auth::user();
$this->validate(request(), [
'name' => 'required',
'password' => 'sometimes|string|min:6'
]);
$user->name = request('name');
$user->password = bcrypt(request('password'));
$user->save();
return back();
}
Any help would be greatly appreciated.

The problem is that if you leave the password field empty, it is still present in the request. But filled with null
Try this instead:
public function update()
{
$user = Auth::user();
$this->validate(request(), [
'name' => 'required',
'password' => 'nullable|string|min:6'
]);
$user->name = request('name');
if(!is_null(request('password'))) {
$user->password = bcrypt(request('password'));
}
$user->save();
return back();
}

Try to add nullable in validation rule
$this->validate(request(), [
'name' => 'required',
'password' => 'sometimes|nullable|string|min:6'
]);
From Laravel docs:
nullable
The field under validation may be null. This is particularly useful
when validating primitive such as strings and integers that can
contain null values.

Related

Laravel test breaks on attaching many-to-many relationship

I have a test which should test the registration of a default User. The test function looks like the following:
public function testCanRegister()
{
$this->json('POST', '/register', [
'name' => 'John Doe',
'email' => 'johndoe#hotmail.com',
'password' => bcrypt('1234')
])
->assertStatus(200)
->assertJsonFragment([
'id' => 3,
'name' => 'John Doe',
'email' => 'johndoe#hotmail.com'
]);
}
It gives me the following error:
Expected status code 200 but received 500. Failed asserting that 200
is identical to 500.
The function it is testing is this:
public function register(RegisterRequest $request)
{
$validatedData = $request->validated();
$user = new User;
$user->name = $validatedData['name'];
$user->email = $validatedData['email'];
$user->password = bcrypt($validatedData['password']);
$user->roles->attach(1); // give User role.
if (!$user->save()) {
return response()->json('Gebruiker kan niet worden geregistreerd', 500);
}
// Create session for the just registered User.
Auth::attempt([
'email' => $user->email,
'password' => $request->json('password')
]);
return response()->json($user, 200);
}
When I comment the line:
$user->roles->attach(1);
the test succeeds. Any ideas on how I can improve my test so it succeeds? The only thing that isn't working is attaching the role.
like in many to many relation doc
$user = App\User::find(1);
$user->roles()->attach($roleId);
so, when you attach, yo attach on relation, not a collection ...
please not that $user->roles is collection of roles, while $user->roles() is a relation ....
just update your statement to:
$user->roles()->attach(1);
Try $user->roles()->attach(1); After saving user first.
like:
$user->save();
$user->roles()->attach(1);

Can't update user information in Laravel

On my current project (a school management system) I want to give admins the ability to register users. Admins can create courses and subjects for example, which I've managed to do using resource controllers. However, I thought I could do the same for users, since the process appears the same to me. That is: I can show, edit, create, update and delete users.
However, I've run into several problems so far. Right now I can create users, but not update them.
Here's my code:
web.php
Route::middleware(['auth', 'admin'])->group(function () {
Route::get('/admin', 'HomeController#admin');
Route::post('register', 'UserController#store');
Route::resources([
'admin/cursos' => 'CursoController',
'admin/turmas' => 'TurmaController',
'admin/semestres' => 'SemestreController',
'admin/materias' => 'MateriaController',
'admin/usuarios' => 'UserController',
]);
});
UserController.php
public function update(Request $request, $id)
{
$rules = array(
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'role' => 'required|string',
'password' => 'required|string|min:6|confirmed',
);
$validator = validator::make(Input::all(), $rules);
if ($validator->fails()) {
// return dd();
return Redirect::to('/admin/usuarios/' . $id . '/edit')
->withErrors($validator);
} else {
// store
$user = User::find($id);
$user->name = Input::get('name');
$user->email = Input::get('email');
$user->role = Input::get('role');
$user->password = Input::get('password');
$user->save();
// redirect
Session::flash('message', 'Sucesso!');
return Redirect::to('/admin/usuarios');
}
}
Validation fails every time I try to update user information. What exactly is going on here? I'm relatively new to Laravel, so I'm a bit lost now.
If the request is failing when a user is trying to update their information without changing the email address, you need additional logic to ignore the id for user associated with the email.
Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address.
To instruct the validator to ignore the user's ID, we'll use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit the rules:
Validator::make($data, [
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
]);
Applied to your set of validation rules it would look like:
$rules = array(
'name' => 'required|string|max:255',
'email' => [
'required',
'string',
'email,
'max:255',
Rule::unique('users')->ignore(auth()->id())
],
'role' => 'required|string',
'password' => 'required|string|min:6|confirmed',
);
You have to except the User ID ($id) in email validation, since u use "unique" rule.
you can check the guide in here
https://laravel.com/docs/5.6/validation#rule-unique

I can't change the user's password

If I want to change the password, the codes are working properly, do not
show any mistakes, but it looks incorrect if you want to log in with a new
password. I saw in the database, there was no password change.
public function postPasswordReset(Request $request)
{
$validator = validator::make($request->all(), [
'email' => 'required|exists:users,email',
'password' => 'required|alpha_num|between:6,32',
're-password' => 'required|same:password'
]);
if($validator->passes()){
$user = User::where('email', $request->email)->first();
$user->update(['password' bcrypt($request->password)]);
return redirect()->route('auth.login');
}
return redirect()->back()->withErrors($validator->errors())-
>withInput();
}
In your update method you are using an array to update in a wrong format. Try this one
$user->update(['password' => bcrypt($request->password)]);

Laravel user update problems

Will try make this clear as much as I can.
Im rolled out a make Auth call in order to use the login and registeration function of laravel and later just used the template to provide the needs I wanted that is.
If user is admin he/she can register a new user.
public function openNewUser(){
return view('auth.register');
}
NB. Part for update.
public function registerNewUser(Request $request){
$this->validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:120',
'password' => 'required|min:4|confirmed']);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = encrypt($request->password);
if (Gate::denies('register-user')) {
return redirect()->back();
}
$user->save();
return view('home');
}
Problem 1 - I also want to update user , which is giving problems. The password inputs return empty fields , which i understand. When I try to change it doenst work the confirm password always give a mismatch even though they are the same. When I leave it blank too it doesnt work because the field is required to be filled. I took them off the form and tried if i could edit the email only but only didnt work.
public function userUpdate (Request $request,$user_id) {
$this->validate($request,[
'email' => 'required|email',
'name' => 'required|max:120',
'password' => 'required|min:4|confirmed']);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = encrypt($request->password);
if (Gate::allows('register-user')) {
$user->save();
$user->roles()->attach($request->roles);
return redirect()->route('view_users');
}elseif (Gate::denies('register-user')) {
if (Auth::id() == $user_id) {
$user->save();
$user->roles()->attach($request->roles);
return redirect()->route('view_users');
}else{
return redirect()->back();
}
}
}
Problem 2. I just realized all logins I am doing with my new registration gives These credentials do not match our records.Even though the credentials are there and was registered correctly.
I am using the login provided by laravel but I created my own registration.
Please how can I edit and update my users and also be able to login after registration
What version of Laravel are you using?
Here is my (v5.3) register() method in RegisterController.php, at least part for registration:
public function register(Request $request)
{
...
// save and login user
$user = $this->create($request->all());
$this->guard()->login($user);
...
}
...
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'lastname' => $data['lastname'],
'phone' => $data['phone'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
and the login() method from LoginController.php
public function login(Request $request)
{
$credentials = $this->credentials($request);
...
if ($this->guard()->attempt($credentials, $request->has('remember'))) {
return $this->sendLoginResponse($request);
}
}
Hopefully I haven't miss anything.
Keep in mind that things have changed here from version 5.2.
I found out what was wrong , Since I am using Laravel's login my registration had to use bycrypt for the encryption which is what Laravel registration was using , but I was using encrypt when I created my own registration so there was a conflict when logging in. (Remembere I was using Laravels login not my own written Login). I hope this helps someone

Laravel validation differences on update and save

I'm using Jeffrey Way's model validation (https://github.com/JeffreyWay/Laravel-Model-Validation) to validate both on save and update. With this method, let's say you fill a update some fields on an entry, then call the save() method, the validation will run on all the fields currently set on the entry. But if the validation requires a field, say the email address, to be unique, the validation will fail because it already exists:
User.php:
protected static $rules = [
'email' => 'required|email|unique:users',
'firstname' => 'required',
'lastname' => 'required'
];
Controller.php:
// Get user from id
$user = User::find($id);
// Update user
$user->update($data);
// Validation when model is saved, via Way\Database\Model
if ($user->save())
{
return Response::json([
'data' => $user->toArray()
], 200);
}
if ($user->hasErrors())
{
return Response::json([
'errors' => $user->getErrors()
]);
}
Will return errors because the email address failed the validation. So, with this method, how do you tell the validator to ignore the unique rule for the email?
I think I use similar behaviour with different approach. Using this model, I thing you shold override the validate method to get the rules from a custom method, in witch you could set your new rules for existing models.
Something like this could work:
protected function processRules($rules = array()) {
$result = [];
if (empty($rules)) {
$rules = static::$rules;
}
// Add unique except :id
$replace = ($this->exists()) ? ',' . $this->getKey() : '';
foreach ($rules as $key => $rule) {
$result[$key] = str_replace(',:' . $this->getKeyName(), $replace, $rule);
}
return $result;
}
And override your validate method to call the proccessRules method.
public function validate() {
$v = $this->validator->make($this->attributes, $this->processRules(static::$rules), static::$messages);
if ($v->passes()) {
return true;
}
$this->setErrors($v->messages());
return false;
}
So now, you can define your email rule as required|email|unique:users:id, and when its a new User the rule should be required|email|unique:users and when you update the User with id 1234 the rule will be required|email|unique:users:1234.
I hope it works fine for you.
I've had this problem! I decided the problem on their own.
protected static $rules = [
'email' => $user->email == Input::get('email') ? 'required|email' : 'required|email|unique:users',
'firstname' => 'required',
'lastname' => 'required'
];
You cannot do it using this package, because you need to pass id for the unique rule. You could do it this way:
protected static $rules = [
'email' => 'required|email|unique:users,email,{id}',
'firstname' => 'required',
'lastname' => 'required'
];
and extend this model to add your custom validation method to replace {id} with id attribute

Resources