I have a model with a mobileNumber property. the mobile number is unique and the validation rules are:
public static $rulesForEdit = array(
'firstName' => 'required|min:5',
'lastName' => 'required|min:5',
'mobileNumber' => 'required|min:5|unique:admin,mobileNumber|numeric'
);
when I update the model, I do this:
$data = array('firstName' => Input::get('firstName'),
'lastName' => Input::get('lastName'),
'mobileNumber' => Input::get('mobileNumber')
);
$validation = Validator::make($data, Admin::$rulesForEdit);
if($validation->passes()){
$admin = Admin::find($id);
$admin->firstName = Input::get('firstName');
$admin->lastName = Input::get('lastName');
$admin->mobileNumber = Input::get('mobileNumber');
$admin->update();
return Redirect::to("restaurants/admins/".$admin->id);
}else{
return Redirect::back()->withInput()->withErrors($validation);
}
The problem that I keep getting a validation error message states that : The mobile number has already been taken, which is correct, but the mobile is belongs to the same model that I am updating, there is no other model that took this mobile number, just the one that I want to update. In other words, I am updating the firstname and the last name but not the mobile number,
To force the Validator to ignore unique rule for a given id you may pass the id of that recored which is being validated, for example:
'mobileNumber' => 'required|min:5|numeric|unique:admin,mobileNumber,50'
This, will not check uniqueness of the model if the id is 10, so when you are updating the model you need to pass the id of the current model to ignore the unique rule on this model:
'mobileNumber' => 'required|min:5|numeric|unique:admin,mobileNumber,' . $id
// Replace the Model with the name of your model within the controller
// update method before the validation takes place
Model::$rules['mobileNumber'] = 'required|min:5|numeric|unique:admin,mobileNumber,' . $id;
Related
I'm trying to make a unique validator to check against a specific product. Like:
// Validate Request for name and url
$this->validate($request, [
'nome' => 'bail|required|min:2|unique:produto,name',
'url' => 'required|unique:produto',
]);
// Grab the user->id
$user_id = Auth::user()->id;
// Create a new product
if ($product = Product::create([
'user_id' => $user_id,
'name' => $request['nome'],
'url' => $request['url'],
'is_active' => $request['is_active'],
])) {
flash()->success('Produto criado.');
} else {
flash()->error('Não foi possivel criar produto.');
}
// Check if $request data is unique at above created product
$this->validate($request, [
'addmore.*.plataforma' => 'required|unique:plataforma_produto,plataforma_id,' . $product->id . ',id,product_id',
]);
// For each of the addmore.*. fields create an entry on DB
foreach ($request->addmore as $value) {
Plataformaprod::create([
'product_key' => $value['product_key'],
'basic_authentication' => $value['basic_authentication'],
'codigo_produto' => $value['codigo_produto'],
'plataforma_id' => $value['plataforma'],
'product_id' => $product->id,
]);
}
return redirect()->route('products.index');
Checking the comments inside my code its basically doing this:
Validate $request for name and url
Grab the user->id
Create a new product
(this is what I can't get to work) RUN THE UNIQUE RULE JUST AGAINST A SPECIFIC PRODUCT_ID AND CHECK IF IT HAS UNIQUE PLATAFORMA_ID ENTRIES!
Couldn't make the validation rule to work properly so I found this solution:
Created a unique index between the product_id and plataforma_id inside my migration file.
Created a try catch encapsulating the hole store method.
Catch the $e and turn it to a 500 error message saying: "The product already have a plataforma_id with that ID. Just added the first
record, change it's info in Edit page. It this error persists contact
dev#"
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 ));
:-)
Here is my Rule :
Table Name is : company_info
I have only two fields CompanyID and Telephone
In the update section, i want to check whether the Telephone Number exists for other columns and if the own field have it i don't want to check it. (Currently it checks the own data and returning with Telephone number was taken already).
'Telephone' => 'unique:company_info',
Then i tried with the below rule
But i miss in the
'Telephone' => 'unique|unique:company_info,CompanyID,'.$companyid)
or
'Telephone' => 'unique|unique:company_info,Telephone,'.$companyid)
or
'Telephone' => 'unique|unique:company_info,Telephone,'.$Telephone)
Here is my Code :
$companyid = Input::get('CompanyID');
$Telephone = Input::get('Telephone');
$rule = array(
'Telephone' => 'unique|unique:company_info,CompanyID,'.$companyid
)
$validator = Validator::make($data,$rule);
if ($validator->fails())
{
$messages = $validator->messages();
return "0"."||".$messages = $validator->messages()->first('Telephone');
}
While the update query i need to check for the unique rule except the given id
I refered this one http://laravel.com/docs/4.2/validation#rule-unique
But i am not getting return on $validator = Validator::make($data,$rule);
How can i check for the unique value except the own column
I believe you have the wrong syntax for unique validation
it should be
'Telephone' => 'unique:company_info,CompanyID,'.$companyid
or
'Telephone' => 'required|unique:company_info,CompanyID,'.$companyid
and not
'Telephone' => 'unique|unique:company_info,CompanyID,'.$companyid
Can try this as the Laravel Validation provides us various features
$companyid = Input::get('CompanyID');
$Telephone = Input::get('Telephone');
$data = array('companyid'=>$companyid, 'Telephone'=>$Telephone );
//FOR INSERTING NEW DATA
$rule = array(
'Telephone' => 'required|unique:company_info,Telephone,{:id}'
);
$validator = Validator::make($data,$rule);
//FOR UPDATING AN EXISTING DATA
public static function rule ($id, $merge=[]) {
return array_merge(
[
'Telephone' => 'required|unique:company_info,Telephone,'.$id,
],
$merge);
}
$validator = Validator::make($data,self::rule($id));
Comment for errors...
Try following code
'Telephone' => 'unique:company_info,Telephone,'.$companyid.', CompanyID';
{rule} =>
'unique:{table_name},{unique_column_name},{except_column_value},{except_column_name}'