James
James

Reputation: 16339

Unique validation across two fields

I'm building a website in Laravel 5 where a user can create a character by choosing a first name and a last name.

I've built some validation rules in around this, but am a little stumped on implementing unique validation as I need it to validate their full name, which is across two columns in my database. For example, a user can create a character called "Jon Snow", but the validation would need to check that the combination of those two fields was unique as someone else may want to create the character "Jon Doe".

I realise now whilst I write this that I could just combine the two columns in to one, and then have validation working on that.

But before I go down that route, is there any way to run validation across two fields like I need?

Below is my validation:

public function store(Request $request)
    {
        $character = new Characters;

         $validator = Validator::make($request->all(), [
            'firstname' => 'required|between:2,15',
            'lastname' => 'required|between:2,15',
        ], [
            'firstname.required' => 'You need to provide a first name!',
            'lastname.required' => 'You need to provide a last name!',
            'firstname.between' => 'The first name must be between :min - :max characters long.',
            'lastname.between' => 'The last name must be between :min - :max characters long.',
        ]);

Upvotes: 1

Views: 761

Answers (2)

Pᴇʜ
Pᴇʜ

Reputation: 57683

Have a look at this package felixkiss/uniquewith-validator. It contains a variant of the validateUnique rule for Laravel, that allows for validation of multi-column UNIQUE indexes.

Upvotes: 2

Sid
Sid

Reputation: 5833

just an idea, after validation,

$firstName = Input::get('firstname');
$lastName = Input::get('lastname');

$whereStatement = ['firstname' => $firstName, 'lastname' => $lastname];

Now use query

$user = DB::table('yourtablename')->where($whereStatement)->count()

if ($user > 1){
 //then redirect back user saying the name must be uniqe
}
else{
//save data to database
}

Upvotes: 0

Related Questions