Validating boolean with Laravel Validation - validation

I have a login form with
username, password and remember me
remember me is a checkbox (true or false).
How do I create the validation rule in Laravel?
http://laravel.com/docs/validation#basic-usage
The only relevant one it seems was in and you specify the values but the values in this case are booleans and using this method they would be specified as string?
in:true,false

There's a validator for boolean. Assuming you're using one of the packages that simplifies model validation, e.g. EsensiModel, it's as simple as adding the following to your Model:
protected $rules = [
'email' => 'required|email',
'password' => 'required',
'remember_me' => 'boolean',
];

You may try something like this:
$rules = array('email' => 'required|email', 'password' => 'required');
$inputs = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
$validator = Validator::make($inputs, $rules);
if($validator->fails()) {
return Redirect::back()->withInput()->withErrorts($validator);
}
else {
$remember = Input::get('remember', FALSE);
if(Auth::attempt($inputs, !!$remember)) {
// Log in successful
return Redirect::to('/'); // redirect to home or wherever you want
}
}
I've used email which is recommended but if you use username other than email then just change the email to username and in the rule for username use something like this:
'username' => 'required|alpha|min:6' // Accepts only a-z and minimum 6 letters

Related

how to edit user email in laravel

i want to edit my user email in laravel, but when i submit the form and then it gives me an error message
The selected Email is invalid.
what do I have to do?
whats wrong with this code?
//in Create Function
'email' => 'required|email|unique:users,email',
//in Update Function is this correct?
'email' => 'required|email|exists:users,email',
Controller
This is my userController for update users
public function update(Request $request, User $user)
{
$validator = Validator::make(
$request->all(),
[
'name' => 'required|string|max:30',
'email' => 'required|email|exists:users,email',
'role' => 'required',
'avatar' => 'required|string|max:150'
],
[],
$this->attributes()
);
if ($validator->fails()) {
$request['role'] = Role::select('id', 'name')->find($request->role);
return redirect()
->back()
->withInput($request->all())
->withErrors($validator);
}
DB::beginTransaction();
try {
$user->update([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'avatar' => parse_url($request->avatar)['path'],
]);
$user->syncRoles($request->role);
Alert::toast(
__('posts.alert.delete.message.success'),
'success'
);
return redirect()->route('users.index');
} catch (\Throwable $th) {
DB::rollBack();
Alert::toast(
__('posts.alert.delete.message.error', ['error' => $th->getMessage()]),
'errors'
);
return redirect()
->back()
->withInput($request->all())
->withErrors($validator);
} finally {
DB::commit();
}
}
You still want a unique validator, so the user can't update their account to someone else's email address and cause a conflict.
However, to prevent it from failing when the user isn't updating their email address (it would fail the unique validation, because a record already exists with that email - the user's own), you'll want to exempt the user's current record from the validation.
https://laravel.com/docs/9.x/validation#rule-unique
See "Forcing A Unique Rule To Ignore A Given ID":
// at the top of your file
use Illuminate\Validation\Rule;
'email' => [
'required',
'email',
Rule::unique('users')->ignore($user->id),
]
You're validating the request requiring the email to exist in the table :
'email' => 'required|email|exists:users,email',
You need to specify unique in order to check the value is not used in the table (same as creation)
'email' => 'required|email|unique:users,email',
You can't do either
'email' => 'exists:users,email'
or
'email' => 'unique:users,email'
for update function. because if you don't change the email you have to submit the old email to the controller which is not "unique" and if you do change it then it doesn't "exist" in the database.
Instead try it like this:
'email' => ['required', 'email', Rule::unique('users', 'email')->ignore($user)],
It means the email should be unique unless it is the email from current user.
See the Laravel docs for more information on this:
https://laravel.com/docs/9.x/validation#rule-unique

error getting a user existing in laravel sanctum

I have a error, I'm using sanctum and I want to check that the email does not exist
the if returns an empty array but the if is satisfied because it returns true
$mail = $request->input(['email']);
if ($search = User::where('email', $mail)->get()) {
return response()->json(['msg' => 'account already exist'], 409);
} else {
$validate = $request->validate([
'name' => 'required|string|',
'email' => 'required|string',
'password' => 'required|string'
]);
}
any solution?
Why not use the Laravel validation since this looks more like validation, so something like:
$request->validate([
'name' => 'required|string|',
'email' => 'required|string|email|unique:users,email',
'password' => 'required|string'
]);
with this you don't need to do an if else. You can check the Laravel docs on https://laravel.com/docs/8.x/validation#introduction for more details

Laravel validation required_if is not working

I have the email and password fields in which I only want them to be required if the add_user field value is 1. This is my validation:
public function rules() {
return [
'add_user' => ['required'],
'password' => ['required_if:add_user,1', 'min:8'],
'email' => ['required_if:add_user,1', 'email', 'max:255'],
];
}
This one is not working, it always errors even if the value is 0. I fill out the add_user value using jquery. I have a drop down that if the user clicked from the options, add_user value is 0, but if thru input, value is 1. Values are correct but the validation isn't working. Can someone help me figure this out?
Okay. Got it.
I added a nullable validation property and now it works.
return [
'add_user' => ['required'],
'password' => ['required_if:add_user,1', 'min:8', 'nullable'],
'email' => ['required_if:add_user,1', 'email', 'max:255', 'nullable'],
];
Hope this will help someone, someday.
We are checking two fields that are not dependent to each other means if user_id!=1 there will be some other validation on password and email so we need to check it by this way
$rules = [
'type' => 'required'
];
$v = Validator::make(Input::all(),$rules);
$v->sometimes('password', 'required|min:8', function($input) {
return $input->type == '1';
});
Here we make an instance of Validator where we checking password is required if user_id ==1 else we no need to validate it.
In Model you can do this.
public function rules(){
return [
'user_id ' => 'required'
];
}
protected function getValidatorInstance() {
$validator = parent::getValidatorInstance();
$validator->sometimes('password', 'required|min:8',
function($input) {
return $input->user_id== 1;
});
return $validator;
}

How to make validation rules for storing and update users if there are unique attributes

I use username as an id to login and made username and email as unique.
Whenever I made username and email, validation rules check coming data and there is no problem with it because username and email would be new and unique.
The problem occurs when I update. when I update the attributes, I don't need to change the username mostly but the rules are expecting unique, username.
what is the best practice for updating unique attributes with validation rules?.
Update user method
public function updateUser($req, $id)
{
$user = User::where('user_id', $id)->firstOrFail();
$user->username = $req->input('username');
$user->password = Hash::make($req->input('password'));
$user->email = $req->input('email');
$user->first_name = $req->input('first_name');
$user->last_name = $req->input('last_name');
$user->phone = $req->input('phone');
$user->emergency_phone = $req->input('emergency_phone');
$user->profile_photo = $req->input('profile_photo');
$user->role = $req->input('role');
$user->status = $req->input('status');
$user->save();
return $this->filterUsers([$user]);
}
Rules
protected $rules = [
'username' => 'required|max:20|unique:users',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required',
// **in Production **
// 'password' => [
// 'required',
// 'min:6',
// 'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/',
// 'confirmed'
// ],
/**
* Three of the five rules.
* English uppercase characters (A – Z)
* English lowercase characters (a – z)
* Base 10 digits (0 – 9)
* Non-alphanumeric (For example: !, $, #, or %)
* Unicode characters
*/
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:5',
'role' => 'required'
];
You can use
'username' => 'required|max:20|unique:users,username,' . $id',
if your users table primary key is id, if it is something else like user_id, then it will become
'username' => 'required|email|unique:user,username,' . $request->input('user_id') . ',userid',
so syntax is
'input_field' => 'unique:<table name>,<column name for this input field>, <unique id>, <unique id column in table>';
At edit time it will check for a unique username so we avoid unique for a current edit id
In the update method your validation rules as per below:
protected $rules = [
'username' => 'required|max:20|unique:users,username,' . $id',
'email' => 'required|string|email|max:255|unique:users,email,' . $id',
'password' => 'required',
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:5',
'role' => 'required'
];
You need to use laravel validator class in controller Use Validator;
And use something like this:
$error = Validator::make($req->all(), $rules);
More examples here in docs of Validation.

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