Home > Software engineering >  Laravel validation rule to enforce unique combinations?
Laravel validation rule to enforce unique combinations?

Time:01-27

I have two columns A & B in the same table. Column B can accept only unique values for each value of Column A.

column A column B
1 8
1 52
1 8 not allowed because value 8 in Column B has already been set for value 1 in column A
2 78
2 2
2 78 not allowed because value 78 in Column B has already been set for value 2 in column A

etc ...

I'm trying to write a validation rule that can do this verification but I'm having trouble.

CodePudding user response:

This is easy enough to do with a closure added to the unique rule. Assuming you're using form request validation:

public function rules(): array
{
    return [
        'A' => [
            Rule::unique('table')->where(function ($query) {
                $query->where('B', $this->B);
            }),
        ],
    ];
}

CodePudding user response:

If you want to do this in a validator, use a custom validation rule:

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    // Change column_b here to the name of your input
    'column_b' => function ($attribute, $value, $fail) use ($request) {
        $columnB = $value;
        // Change column_a here to the name of your input
        $columnA = $request->input('column_a');

        $records = DB::table('YOUR_TABLE')
            ->select('*')
            // Change column_a here to the name of column A in your database
            ->where('column_a', $columnA)
            // Change column_b here to the name of column B in your database
            ->where('column_b', $columnB)
            ->count();

        if($records > 0) {
            $fail("not allowed because value $columnB in Column B has already been set for value $columnA in column A");
        }
    },
]);
  •  Tags:  
  • Related