I need to validate user table in which not repeated combination of (firstname and lastname). for example:- firstname=dc lastname=patel already exist in table. i need to prevent same entry next time.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Finally I have perfect solution for this.
$validationRule = ['first_name' => 'required','last_name'=>'required'];
$validationMsg = ['first_name.required' => 'First Name is required', 'last_name.required' => 'Last Name is required'];
$validation = Validator::make(['first_name' => $firstName, 'last_name' => $lastName], $validationRule, $validationMsg);
$validation->after(function ($validation) use ($firstName, $lastName) {
$checkName = User::where('first_name', $firstName)->where('last_name', $lastName)->get();
if (count($checkName) > 0) {
$validation->errors()->add('first_name', 'User already exists, please enter another user.');
}
});
if ($validation->fails()) {
foreach ($validation->errors()->all() as $error) {
$message = $error;
}
return response(\Helpers::makeAjaxResponse(false, $message));
} else {
//Save record code here
}
回答2:
You can use something simular to composite UNIQUE key in table if database provide this possibility.
http://dev.mysql.com/doc/refman/5.7/en/multiple-column-indexes.html
回答3:
with using laravel unique validation rule how can you allow users with same lastname but not firstname for registeration?
unique.firstname
回答4:
First check records count with the given firstname and lastname. If the count is '0' save the record or else show message.
Here is some code hint
$users = DB::table('users')
->where(['firstname' => 'dc', 'lastname' => 'patel'])
->count();
if($users === 0) {
// save the record.
} else {
// Show message
}
回答5:
Since Laravel 5.5 you can use elegant Rule class like:
use Illuminate\Validation\Rule;
// ...
$firstNameUniqueRule = Rule::unique('users')->where('last_name', request()->get('last_name', ''));
$rules = [
'first_name' => ['required', $firstNameUniqueRule],
'last_name' => 'required',
];