Issue
When i validate the phone number i the controller then it is working but it increases the lines of code and i also have to write the callback functions, But i don't want to write the callbacks,instead i want to do it in the model, is there any way to do it??
'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.');
}
}
},],
Solution
I think you should be able define the function in your model as a static function that returns a closure, so then you can call it to get the closure and pass it on as a callback.
// 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.');
}
}
};
}
Then you can use it in the validation as
'phone' =>['required',"regex:/^\(?[\d]{3}\)?[\s-]?[\d]{3}[\s-]?[\d]{4}$/", MyModelClass::myValidationClosure($id)]
Answered By - Helioarch Answer Checked By - Katrina (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.