Laravel unique validation fails on update - php

I am using laravel 5.7 and using form request but i have a unique branch_name in my database as well as unique slug but every time on update valdiation erorr .branch name already exist
public function rules()
{
switch($this->method()) {
case 'DELETE':
return [
'slug'=>'required',
];
case 'POST':
case 'PUT':
case 'PATCH':
return [
'branch_name'=>'required|max:255|unique:branches,branch_name,id'.$this->id,
'branch_address'=>'required',
];
default:
break;
}
}
and also i tried the following but no use
'branch_name'=>'required|max:255|unique:branches,branch_name,'.$this->id,
and
'branch_name'=>'required|max:255|unique:branches,branch_name,slug'.$this->slug,
also i have a hidden value for both id as well as for slug even i printed in on rule method i can see id and slug

This will do:
use Illuminate\Validation\Rule;
'branch_name' => [
'required|max:255',
Rule::unique('branches')->ignore($this->route('branch')),
]
Replace "branch" with route parameter name from your edit route of web.php.
You can use this validation in add and edit both.
if your database field name is different then send the name as the second parameter in ignore function. Like
Rule::unique('branches')->ignore($this->route('branch'), 'branchName'),
Details: Laraval Validation unique
Hope this helps.

Try this one
use Illuminate\Validation\Rule;
'branch_name' => [
'required|max:255',
Rule::unique('branches')->ignore($branches->id),
],

unique:table,column,except,idColumn
The field under validation must be unique in a given database table. If the column option is not specified, the field name will be used.
validation
'branch_name' => 'required|max:255|unique:branches,branch_name,' . $this->id . ',id',
OR
'branch_name'=>'required|max:255|unique:branches,branch_name,' . $this->slug . ',slug',

Related

Laravel validator, unique value when update info

So i have validator that checks if reg_number is unique. I use it for creating new entries (that part works). However, when i try to update an existing one using another form - i get error that reg_number already exists (logical). So my question is how to edit the rule that it would make an exception when i try to update (update other fields and keep reg_number the same) and not create a new one. Found something in other forums (added at the end of the rule) but its not working. Code below:
public function rules()
{
return [
'reg_number'=>'required|max:6|min:6|unique:cars'.$this->cars['reg_number'],
'brand'=>'required',
'model'=>'required'
];
}
Cheers!
There's an example as to how to do this in the Laravel docs.
Basically, you add the ID for the model instance you want to be excepted from this rule. E.g.:
public function rules()
{
return [
'reg_number' => ['required', 'max:6', 'min:6', 'unique:cars,reg_number,' . $this->id],
'brand' => ['required'],
'model' => ['required'],
];
}

Laravel 5 Validations

I want to validate my form fields using laravel 5.
Form field 1 -> User ID :
Form Field 2 -> Other Name :
Either of the form field is required.
i mean if user id is present other name should be blank and if other name is present user_id should be blank.
I am trying to use:
$validator = Validator::make(
[
'user_id ' => $user_id,
'user_name' => $user_name
], [
'user_id' => 'required_without:user_name',
'user_name' => 'required_without:user_id'
]);
if ($validator->fails()) {
return Utility::validation_err($validator);
}
While updating record even if user id is present it gives me error user id is required when other name is not present. also if i am filling out both it accepts both. It should accept one of both fields.
Any help will be appreciated.
You can use your own validation rule, for exmaple "only_one_id_name_required". It should be applied to both of fields. Next put extend Validator in App\Providers\AppServiceProvider
Validator::extendImplicit('only_one_id_name_required', function($attribute, $value, $parameters, $validator) {
return (request()->has('user_id') xor request()->has('user_name'));
});
Use extendImplicit() instead of extend() to cover empty fields request.

Laravel 5.2 - validation - One of the fields is required

Take a scenario,
There are 2 fields available in the form.
1) input type file for manual upload.
2) input type = text to enter youtube video url.
is it possible using laravel built-in validations so that validation will be fired if user has left both fields empty!
I have gone through https://laravel.com/docs/5.3/validation but could not find what I wanted.
In your controller, you could do something like this:
$validator = Validator::make($request->all(), [
'link_upload' => 'required|etc|...',
]);
$validator2 = Validator::make($request->all(), [
'file_upload' => 'required|etc|...',
]);
if ($validator->fails() && $validator2->fails()) {
// return with errors
}
Try required-without-all validation rule. As given in documentation:
The field under validation must be present only when the all of the other specified fields are not present.
Assuming your fields name are url and file, your rule would be like below:
$rules = [
'url' => 'required_without_all:file',
'file' => 'required_without_all:url'
];
required_without:foo,bar,...
The field under validation must be present and not empty only when any of the other specified fields are not present.
Try this,
In youre update method add this
$this->validate($request, [
'fileName'=>'required',
'urlName'=>'required'
]);
dont forget to set the fillable in your model
protected $fillable = ['fileName','urlName'];
Hope this helps

Laravel validate unique if id is the same

I have a table/model that contains multiple albums per user.
Is there a way to say that the column title should be unique, but only for the rows that have the same user_id?
Example: http://pastebin.com/8dvM4a1T
As you can see in the example, the user with the id of 2 has created 2 albums, with the same title. I don't want that to be allowed, that's why I'm wondering if there's a way to deny that with the validator from Laravel?
I tried this, but that did not work.
// Validator
$validator = Validator::make($input, [
'title' => 'required|min:1|max:255|unique:galleries,title,'. Auth::user() -> id .',user_id',
'description' => 'min:1|max:255'
]);
Any help appreciated, thanks.
Your code should be something like:
'title' => 'unique:galleries,title,NULL,id,user_id,'.Auth::user() -> id.'',
Or, you can write a custom rule
Reference here
The approach with the default unique rule does not work because the rule expects the column value to be passed as the third parameter, so in your case it would check if the title column is equal to the Auth::user()->id value which is not what you want.
You can create you own custom validation rule by adding the following code to the boot method of the App\Providers\AppServiceProvider class:
Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
// Get the parameters passed to the rule
list($table, $field, $field2, $field2Value) = $parameters;
// Check the table and return true only if there are no entries matching
// both the first field name and the user input value as well as
// the second field name and the second field value
return DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
});
Now you can use the unique_custom (or you can name it whatever you like) rule like so:
$validator = Validator::make($input, [
'title' => 'required|min:1|max:255|unique_custom:galleries,title,user_id,' . Auth::id(),
'description' => 'min:1|max:255'
]);
The rule expects the parameters to be the following:
the 1st parameter to be the table name, which in this case is galleries
the 2nd parameter to be the field name that is supposed to be unique and for which the value comes from the user input, which in this case is title
the 3rd parameter to be the second field name that will be added to the query conditions, which in this case is user_id
the 4th parameter to be the value of the field name passed as the third parameter
Also you can use Auth::id() since that is the short form of Auth::user()->id.
You can read more about Custom Validation rules in the Laravel Documentation.
Laravel 5.3 and above
use Illuminate\Validation\Rule;
'email' => Rule::unique('galleries')->where(function ($query) {
$query->where('user_id', Auth::id());
})
Laravel 9
use Illuminate\Validation\Rule;
Rule::unique('galleries')->where(fn ($query) => $query->where('user_id', Auth::id()))

Laravel rule for unique excluding blank or null

I have a user model that needs to have unique email addresses but I also want to allow them to be left blank in case the user has no email...I see in docs there is a way to make a rule for unique and an exception for an id...but I'm not sure how to make this allow null or blank but unique if it is not. Sorry seems like this is simple but I can't think of the answer.
public static $adminrules =
'email' => 'email|unique:users,email,null,id,email,NOT_EMPTY'
);
Edit It may be that using the rule without required is enough since a blank or null would pass validation in those cases. I might have a related bug that making it so I can't add more than 1 blank email, so I can't verify this.
public static $adminrules =
'email' => 'email|unique:users'
);
I tried this. Adding 'nullable' before 'sometimes'.
$validator = Validator::make($request->all(), [
'email' => 'nullable|sometimes|unique:users',
]);
You should try this:
$v->sometimes('email', 'email|unique:users,email', function($input)
{
return !empty($input->email);
});
$v is your validator object and you basically say that in case the email field is not empty it should also be unique (there shouldn't be a users table record with this value in email column).
In your Requests/UserRequest you'd have something like
public function rules()
{
return [
'email' => [
'nullable',Rule::unique((new User)->getTable())->ignore($this->route()->user->id ?? null)
]
];
}
The usage of nullable is what allows the field to be nullable. The other part is to check if the email is unique in the User model table.
If you wish to validate if the field is unique
between two fields please refer to this answer.
in another table, then add the following to your rules
'exists:'.(new ModelName)->getTable().',id'
You should try to change your structure of database to make the field email is nullable. And in the rules try this :
$this->validate($request,
[
'email' => 'email',
]
);
if(isset($request->address))
{
$this->validate($request,
[
'email' => 'email|unique:users'
]
);
}

Categories