Laravel Validator realizes the uniqueness of two or more field joint indexes

  • 2021-12-09 08:33:42
  • OfStack

Laravel Validation is quite easy to use, Validator can be very convenient to verify the form, it provides unique uniqueness verification, but only one field can be verified by default, that encounter two or more fields of joint index, need to meet complex conditions uniqueness how to achieve

Implementation method of complex uniqueness of Validator

We can customize validation rules with custom Rule, such as this:


[...]
$where = [
      'name' => $request->name,
      'phone' => $request->phone
    ];
$this->validate($request, [
    "phone" => [
        "required",
        Rule::unique('table_name')
            ->where(function ($query) use ($where) {
                return $query->where($where);
            })
    ],
]);
[...]

First of all, we change the original string form into array form, and use Rule to customize new rules in the array. Obviously, unique () method is customized to unique, and then the parameter is the name of the table, followed by an where function, which uses closures and anonymous functions to query whether the results that meet two conditions at the same time exist and return query results.

In this way, we have completed the custom complex uniqueness verification.

Summarize


Related articles: