Laravel validator implements joint index uniqueness of two or more fields


The validation of laravel is still very easy to use. Using validator can easily validate forms. It provides unique verification, but only one field can be verified by default. How can we achieve the uniqueness of complex conditions when encountering the joint index of two or more fields

The implementation of validator’s complex uniqueness

We can use custom rules to customize validation rules, such as this:

$where = [
      'name' => $request->name,
      'phone' => $request->phone
$this->validate($request, [
    "phone" => [
            ->where(function ($query) use ($where) {
                return $query->where($where);

First of all, we change the original string form to array form, and use rule to customize new rules in the array. It is obvious that the unique () method comes from the definition of unique, and then the parameter is the name of the table, followed by a where function, which uses closures. Anonymous function queries whether the results satisfying both conditions exist, and returns the query results.

In this way, we complete the custom complex uniqueness verification.


The above is the Laraway validator introduced by Xiaobian to you to realize the unique joint index of two or more fields, hoping to help you. If you have any questions, please leave a message to me, and Xiaobian will reply to you in time. Thank you very much for your support of the developepaer website!
If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!

Recommended Today

The way of nonlinear optimization

Mathematical knowledge 1、 Nonlinear functionLinear function is another name of a function of first degree, then nonlinear function means that the function image is not a function of a straight line.Nonlinear functions include exponential function, power function, logarithmic function, polynomial function and so on. 2、 Taylor expansion1. Taylor formula:Taylor’s formula is to add a_ The […]