1

I'm trying to validate a form, where there are two mandatory columns whose combination must be unique in the table. Validator should also ignore the case of the input.

$data = request()->validate([
     'dc_name' => 'required',
     'dc_code' => ['required',
            Rule::unique('dcs')->where(function ($query) use ($request) {
            $query->where(DB::raw('lower(dc_name)'), strtolower($request->dc_name));
        })
     ]                                     
]);

Combination of dc_name and dc_code should not be repeated in the dcs table. The given code works with dc_code. But I don't want to repeat same thing for dc_name. Is there any simpler way to do this?

2 Answers 2

0

You can create a unique rule and then apply it in the rules array

$uniqueCodeRule = Rule::unique('dcs')->where(function ($query) {
    return $query->where(DB::raw('lower(dc_name)'), strtolower(request()->dc_name))
                 ->where(DB::raw('lower(dc_code)'), strtolower(request()->dc_code));
});

$data = request()->validate([
    'dc_name' => ['required', $uniqueCodeRule],
    'dc_code' => 'required'
]);

You can apply this rule to only 1 parameter as both (dc_name and dc_code) are included the ORM.
Also you can explore more about validation rule in doc.

Sign up to request clarification or add additional context in comments.

Comments

0

You can try this approach to update your code.

$query->whereRaw('LOWER(dc_name) = ? AND LOWER(dc_code) = ?', [
    strtolower(request()->input('dc_name')),
    strtolower(request()->input('dc_code'))
]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.