I create a custom validator class that may return with diffrent cases, so i need to set custom error messages before each one these return.
I created this Validator Class
class UserConfirmationMessageValidator extends Validator
{
public function canPassTheMessageConfirmation($attribute, $value, $parameters, $validator){
$confirmationKey = $validator->getData()["confirmationKey"];
$phoneNumber = $validator->getData()["phone"];
if(!isset($confirmationKey)){
if(case1){
// must set custom error message for this case
}else {
// must set custom error message for this case
}
return false;
}else {
if(case2){
return true;
}else{
// must set custom error message for this case
}
}
// can return with message that define in (AppServiceProvider => boot), if any cases
return false;
}
}
This is my AppServiceProvider Class
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
// some other validators
Validator::extend('canPassTheMessageConfirmation', UserConfirmationMessageValidator::class."@canPassTheMessageConfirmation","you will receive sms. please wait");
}
}
My Controller where the rules set
public function store(Request $request) // kullanıcı kaydetme
{
$validator = Validator::make($request->all(), [
'area1' => 'unique:vp_users|required|min:8|max:16|canPassTheMessageConfirmation',
'area2' => 'required|max:255',
'area2' => 'required|max:255',
'area4' => 'required|min:6|confirmed',
'area5' => 'required|date_format:Y-m-d',
'area6' => 'required|max:1',
]);
if ($validator->fails()) {
return response()->json($validator->errors()->first(),400); // Bad Request
} else {
$user = $this->create($request->all());
return response()->json($user, $request->statusCode);
}
}
Dumped output of validator's error, var_dump($validator->errors());
object(Illuminate\Support\MessageBag)[246]
protected 'messages' =>
array (size=1)
'area1' =>
array (size=1)
0 => string 'you will receive sms. please wait' (length=33)
protected 'format' => string ':message' (length=8)
When validator fails with this canPassTheMessageConfirmation rule, validator returns a message : "you will receive sms. please wait" that was defined in AppServiceProvider boot function. I want to change this message in canPassTheMessageConfirmation method of UserConfirmationMessageValidator class, according to my return cases. If my explanation is not clear. I can share more code as your wish.
Validator::make($request->all(), $rules, [ 'area1' => ['canPassTheMessageConfirmation' => "Your Message"]]);return false, but didn't work.Validator::make($validator->getData(), $validator->getRules(), [ 'area1' => ['canPassTheMessageConfirmation' => "Your Message"]]);$validator->errors() method.Validator::make($validator->getData(), $validator->getRules(), [ 'area1' => ['can_pass_the_message_confirmation' => "Your Message"]]);camelCase to snake_case. Give it a shot.