Php 如何在laravel中的模型中编写验证?
当我验证电话号码时控制器工作正常,但它增加了代码行,我还必须编写回调函数,但我不想编写回调函数,而是想在模型中执行,有什么方法可以执行吗Php 如何在laravel中的模型中编写验证?,php,laravel,php-7.2,laravel-6.2,Php,Laravel,Php 7.2,Laravel 6.2,当我验证电话号码时控制器工作正常,但它增加了代码行,我还必须编写回调函数,但我不想编写回调函数,而是想在模型中执行,有什么方法可以执行吗 'phone' =>['required',"regex:/^\(?[\d]{3}\)?[\s-]?[\d]{3}[\s-]?[\d]{4}$/",function($attribute, $value, $fail) use($id) { if (strpos($value, "-") !== false) {
'phone' =>['required',"regex:/^\(?[\d]{3}\)?[\s-]?[\d]{3}[\s-]?[\d]{4}$/",function($attribute, $value, $fail) use($id) {
if (strpos($value, "-") !== false) {
$exist = User::where([["phone", $value],["id","!=",$id]])->count();
if($exist){
$fail(ucwords($attribute).' is already taken.');
}else{
$result = User::where([["phone", str_replace("-","",$value)],["id","!=",$id]])->count();
($result) ? $fail(ucwords($attribute).' is already taken.') : "";
}
}else{
$exist = User::where([["phone", $value],["id","!=",$id]])->count();
if($exist){
$fail(ucwords($attribute).' is already taken.');
}
}
},],
对于验证来说,最好的解决方案是创建一个单独且易于处理的自定义请求,如下=>
php artisan make:request CustomRequest
请求:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\User;
class CustomRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'phone' => [
'required',
'min:10',
'max':10',
'regex:/^\(?[\d]{3}\)?[\s-]?[\d]{3}[\s-]?[\d]{4}$/',
],
];
}
}
我认为您应该能够将模型中的函数定义为返回闭包的静态函数,这样您就可以调用它来获取闭包并将其作为回调传递
// In the model
public static function myValidationClosure($id){
return function($attribute, $value, $fail)use($id) {
if (strpos($value, "-") !== false) {
$exist = User::where([["phone", $value],["id","!=",$id]])->count();
if($exist){
$fail(ucwords($attribute).' is already taken.');
}else{
$result = User::where([["phone", str_replace("-","",$value)],["id","!=",$id]])->count();
($result) ? $fail(ucwords($attribute).' is already taken.') : "";
}
}else{
$exist = User::where([["phone", $value],["id","!=",$id]])->count();
if($exist){
$fail(ucwords($attribute).' is already taken.');
}
}
};
}
然后您可以在验证中使用它作为
'phone' =>['required',"regex:/^\(?[\d]{3}\)?[\s-]?[\d]{3}[\s-]?[\d]{4}$/", MyModelClass::myValidationClosure($id)]
谢谢,我明白了,但是有没有办法不写我正在使用的回调,因为正如您所建议的那样,它只验证正则表达式,但不会验证数据库中是否存在该数字,或者是否与回调中一样。再次感谢。