Home > database >  How to make two columns of a table requiring to be unique at user request
How to make two columns of a table requiring to be unique at user request

Time:01-18

I have tried validating the user request like this:

$data = $request->validate([
            'fname' => 'nullable',
            'lname' => 'nullable',
            'gender' => 'required',
            'mobile' => 'required|unique:users,usr_name',
            'ncode' => 'nullable',
            'password' => 'required',
            'password_confirmation' => 'required',
        ]);

So as you can see I have said that the mobile filed value must be unique:users,usr_name but I do need to check that it is unique at members table as well (the mbr_mobile column):

unique:members,mbr_mobile

So how to combine these two rules at once?

CodePudding user response:

Just specifying the model name should work.

'mobile' => 'required|unique:User|unique:Members',

But you may specify the column name too.

'mobile' => 'required|unique:User, mobile|unique:Member,mbr_mobile',

CodePudding user response:

You can do it exact,y same way as for users table :

$data = $request->validate([
        'fname' => 'nullable',
        'lname' => 'nullable',
        'gender' => 'required',
        'mobile' => 'required|unique:users,usr_name|unique:members,mbr_mobile',
        'ncode' => 'nullable',
        'password' => 'required',
        'password_confirmation' => 'required',
    ]);

CodePudding user response:

You can use the Rule class to create a custom validation rule that checks for uniqueness across multiple tables. In this case, you would create a rule that checks for uniqueness in both the users table's usr_name column and the members table's mbr_mobile column.

You can create a new rule in your rules folder and call it UniqueMobile.

use Illuminate\Validation\Rule;

class UniqueMobile
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return !(
            DB::table('users')->where('usr_name', $value)->exists() ||
            DB::table('members')->where('mbr_mobile', $value)->exists()
        );
    }
    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute is already taken.';
    }
}

Then you can use this rule in your validation like this:

$data = $request->validate([
            'fname' => 'nullable',
            'lname' => 'nullable',
            'gender' => 'required',
            'mobile' => [
                'required',
                new UniqueMobile
            ],
            'ncode' => 'nullable',
            'password' => 'required',
            'password_confirmation' => 'required',
        ]);

It will check if mobile number is already exists in both users and members table.

  • Related