How to add unique validation on combination of fir

2019-06-03 15:11发布

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.

标签: laravel-5
5条回答
可以哭但决不认输i
2楼-- · 2019-06-03 15:49

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楼-- · 2019-06-03 15:50

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
}
查看更多
趁早两清
4楼-- · 2019-06-03 15:54

with using laravel unique validation rule how can you allow users with same lastname but not firstname for registeration?

unique.firstname

查看更多
老娘就宠你
5楼-- · 2019-06-03 16:10

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
            }
查看更多
闹够了就滚
6楼-- · 2019-06-03 16:11

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',
];
查看更多
登录 后发表回答