This question already has answers here:
Laravel update model with unique validation rule for attribute
(20 answers)
Closed 2 years ago.
I'm having difficulties detecting a unique username. I mean it does work to detect username but I would like to exclude the username validation if the request input username matches with that users current username in database.
Currently, I'm getting: The username has already been taken. despite the fact the its the same username as the one this user has in the database.
Thank you!
Rules
protected $rules = [
'username' =>
'nullable|string|alpha_dash|max:255|regex:/(^([a-zA-Z]+)(\d+)?$)/u|unique:users',
'first_name' => 'nullable|max:150',
'last_name' => 'nullable|max:150',
'location' => 'nullable|max:200',
'password' => 'confirmed'
];
Edit Profile POST method:
$validator = Validator::make($request->all(), $this->rules);
if ($validator->fails()) {
return \redirect()->back()->withErrors($validator->getMessageBag()->toArray())->withInput($request->except('image'));
} else {
$model = \App\User::find(\Auth::user()->id);
On update you can ignore the field as :
'username' =>
'nullable|string|alpha_dash|max:255|regex:/(^([a-zA-Z]+)(\d+)?$)/u|unique:users,' . $user->id,
Or,
'username' => [
'nullable',
'string',
Rule::unique('users')->ignore($user->id),
],
You may pass a different column name as the second argument to the unique method:
Rule::unique('users', 'username')->ignore($user->id),
You may also specify additional query constraints by customizing the query using the where method. For example :
Rule::unique('users')->where(function ($query) {
return $query->where('username', '!=', $request->username);
})
Related
I want to validate a value that I got from a certain form. The value type is text. I want it to match a specific username from the database from the users table, but also to not match the current user's username.
To achieve that, I used the following validation rules:
'username' => [
'required',
'string',
'exists:App\User,username',
'different:' . auth()->user()->username
]
What I've discovered is that whenever the auth()->user()->username value includes a digit, it passes the validation even if request()->username = auth()->user()->username. Is there anything I can do to prevent this from happening?
Thanks in advance.
Use unique like -
Considering id is your user's id.
'username' => 'required|string|unique:username,id,'.auth()->user()->username,
This will check if username is unique or not except this userId.
The answer to this issue was creating own Rule::exists validation, which is shown below:
'username' => [
'required',
'string',
Rule::exists('users')->where(function ($query) {
$query->where('username', '<>', auth()->user()->username);
})
],
I solved a similar problem as follows.
$request->validate([
'email' => ['required', 'email','unique:users,email,'.Auth::id()],
'phone' => ['required', 'unique:users,phone,'.Auth::id()],
]);
This question already has answers here:
Validate array of inputs in form in Laravel 5.7
(6 answers)
Closed 3 years ago.
I am storing data from a form through an array to mysql database. Now I want to alert the user if he missed any field. So how can I alert him?
public function store(Request $request)
{
$holiday = array (
'firstname' => $request->firstname,
'lastname' => $request->lastname,
'startdate' => $request->startdate,
'enddate' => $request->enddate
);
Holiday::create($holiday);
return redirect()->route('holiday.index');
}
You can use Laravel's built in validation functionality for this. In your case, you might want to do something like this:
public function store(Request $request)
{
$holiday = $request->validate([
'firstname' => 'required',
'lastname' => 'required',
'startdate' => 'required',
'enddate' => 'required'
]);
Holiday::create($holiday);
return redirect()->route('holiday.index');
}
Laravel will then ensure that those fields have been provided and if they haven't it will return the appropriate response. For example, if this is an API call it will return a 422 response with the error messages in. Or, if it is not an API call, it will return the user to the previous page and store the errors in the session for you to retrieve.
I'd recommend reading more about Laravel's validation techniques and all the things you can do with it. You can find more information about it here - https://laravel.com/docs/6.x/validation
I wan't to be able to validate a user email address based on certain circumstances.
For example
If a user is being created, the email address must be unique
If a user is being updated but the email address hasn't changed, ignore the unique email rule
If a user is being updated and their email address has changed, it has to be unique
I've had a little look around and I know that I can specify different rules based on the method like so
public function rules()
{
$user = User::find($this->users);
switch($this->method())
{
case 'POST':
{
return [
'user.email' => 'required|email|unique:users,email',
];
}
case 'PUT':
case 'PATCH':
{
return [
'user.email' => 'required|email,
];
}
default:break;
}
}
Is there any way to make it so that in the put/patch case, the rule checks if the email address has been changed, and if it has then it has to be unique?
If not is there a cleaner way of achieving this goal? Maybe without the switch case? Perhaps more in depth validation rules I haven't stumbled across yet?
If i understand you correctly, you want to add unique validation if email changed, if that is the case then you just need to add a condition in validation. If you check unique validation structure it look like this unique:table,column,except,idColumn, check documentation
So the validation will be look like this, when you will create new record $userId will be null but at time of patch it will have value. So this validation will work for both create and patch.
$userId = isset($user) ? $user->id : null;
$rules = [
'email' => 'required|email|unique:users,email,'. $userId.',id',
];
$this->validate($request, $rules);
I had a similar issue and found a tidy way of addressing it in the docs.
My issue was that if a user was already created, the email address claimed it wasn't unique, even if it was already registered to the user.
https://laravel.com/docs/8.x/validation#rule-unique
A few headings down is something like this:
use Illuminate\Validation\Rule;
$request->validate([
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
]);
This does the following:
Validate the email address, make it required and unique, unless the user ID of that row matches this user.
There is a built-in feature for this. You can add the actual user id to the unique constraint, if present. This will ensure that the unique constraint will still work, but it will not fail when the value did not change:
$exists = $user->exists;
$rules = return [
'user.email' => 'required|email|unique:users,email' . ($exists ? ','.$user->id : ''),
];
Internally, this will execute a query like:
SELECT count(id) FROM users WHERE email = 'some-mail#example.com' AND id != 42
The latter part AND id != 42 will only be part of the query when you add the third parameter to the unique validation rule.
You are missing the break; statement after every case. And for Update (PATCH request) you have to pass id also in update request.
public function rules()
{
$user = User::find($this->users);
switch($this->method())
{
case 'PATCH':
{
return [
'user.email' => 'required|email|unique:users,email,'. $user->id.',id',
];
}
break; // change here
case 'PUT': break; // change here
case 'POST':
{
return [
'user.email' => 'required|email,
];
}
break; // change here
default:break;
}
}
$request->validate([
'naam' => 'required|max:190|unique:database_name.table,column_where_you_check_unique,'.$id.',$id_column_reference'
]);
'naam' - form input field name
database_name(optional) - if you have multiple database
table(required) - table name
column_where_you_check_unique(required) - where data is unique
$id(required) - check with id autoincrement
$id_column_reference - column name of $id.
My way:
'slug' => $site->slug !== $request->slug ? 'required|min:4|max:80|unique:sites' : 'required|min:4|max:80'
In your controller methods (store and update) you can use:
$validations = [
'email' => 'required|email|unique:users,email'
];
$this->validate($request, $validations);
You can try this
$exists = Section::where('code', $request->code)->exists();
$isUpdateQuery = (($request->method() == 'PUT') || ($request->method() == 'PATCH'));
$validatedData = $request->validate([
"code" => ['required','unique:sections,code' . (($isUpdateQuery && $exists) ? ',' . $request->code . ',code': '')],
"title" => 'required | json',
"subtitle" => 'required | json',
"btn_title" => 'required | json',
"name" => 'required',
"pageID" => 'required | exists:pages,pageID',
"image" => 'nullable',
"btn_link" => 'nullable',
]);
I am working on a Laravel project and I have the following problem related to validation.
In the past I created this validation rules (related to a new user registration form):
$rules = [
'name' => 'required',
'surname' => 'required',
'login' => 'required|unique:pm_user,login',
'email' => 'required|email|confirmed|unique:pm_user,email',
'pass' => 'required|required|min:6',
'g-recaptcha-response' => 'required|captcha',
];
In particular this rules array contains this rule:
'login' => 'required|unique:pm_user,login',
it seems to me that this last rule check if the inserted login doesn't yet exist into the pm_user table (so it ensure that not exist a row of the pm_user table having the same inserted value into the login column).
Is it? Correct me if I am doing wrong assertion.
If it work in this way now my problem is how to do the opposite thing in another set of validation rule.
In particular I have this other array of rule (defined into a class extendingFormRequest:
public function rules() {
return [
'email' => 'required|email',
'token' => 'required',
];
}
In particular I have to ensure that into the pm_user table yet exist a record having the value of the column named email that is the same of the emai field of the request.
How can I change this request to perform this validation rule?
Laravel 5.4 already has a built in validation rule for this called exists.
https://laravel.com/docs/5.4/validation#rule-exists
I think you are looking for:
'email' => 'required|email|exists:pm_user,email'
These are my rules in my class:
class AppointmentsController extends Controller
{
protected $rules = [
'appointment' => ['required', 'min:5'],
'slug' => ['required', 'unique:appointments'],
'description' => ['required'],
'date' => ['required', 'date_format:"Y-m-d H:i"'],
];
This is in the laravel official docs:
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. You only want to throw a validation error if the
user provides an e-mail address that is already used by a different
user. To tell the unique rule to ignore the user's ID, you may pass
the ID as the third parameter:
'email' => 'unique:users,email_address,'.$user->id.',user_id'
I tried using this in my rules:
'slug' => ['required', 'unique:appointments,id,:id'],
This indeed ignores the current row BUT it ignores it completely. What I want to accomplish is, I want it to ignore the current row only if the slug is unchanged. When it is changed to something that is already unique in another row, I want it to throw an error.
The Unique validator works like that
unique:table,column,except,idColumn
So in your case, you can do it like that:
Get the id you want to validate against, you can get it from the route or with any other way that works for you; something like that
$id = $this->route('id');
'slug' => ['required','unique:appointments,slug,'.$id],
For example we need to update contact info into Users table.
In my model User I created this static method:
static function getContactDataValidationRules( $idUserToExcept ) {
return [
'email' => 'required|email|max:255|unique:users,email,' . $idUserToExcept,
'pec' => 'required|email|max:255',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:8|max:20',
'mobile' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:8|max:20',
'phone2' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:8|max:20',
'recovery_email' => 'required|email|max:255',
];
}
and in my UsersController, into the method that update User I've:
$id = $request->input('id');
$request->validate(User::getContactDataValidationRules( $id ));
:-)