Laravel's Validation is quite useful. Using Validator can easily verify the form. It provides unique uniqueness verification, but can only verify one field by default. When encountering a joint index of two or even multiple fields, how to achieve uniqueness if it needs to meet complex conditions.
Validator complex uniqueness implementation method
We can use custom Rule to customize verification rules, such as:
[...] $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, we change the original string form to an array form, and use Rule to customize new rules in the array. Obviously, the unique() method is customized for unique, and then the parameter is the name of the table, followed by a where function, using a closure. The anonymous function query whether the result that meets two conditions at the same time exists and returns the query result.
In this way, we complete custom complex uniqueness verification.
Summarize
The above is the editor’s introduction to Laravel Validator. It realizes the uniqueness of two or more fields in joint indexes. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!
If you think this article is helpful to you, please reprint it. Please indicate the source, thank you!