How to Change the Key of Validation Error in Laravel

I am new to laravel and working on apis, I have made an api in which i have implemented validation.Everything is working fine but i am stuck on a little thing. I want to to change the key name in the validation error. For example For the “unique” validation error. This is what now showing

enter image description here

I want to rename “email”(text) key with “message”(text)

I have tried so many thing in illuminate/support/validation.php

messagebag.php file but if it changes then error show of “data undefined”.

The links i followed are

https://stillat.com/blog/2018/04/21/laravel-5-message-bags-adding-messages-to-the-message-bag-with-add

https://laracasts.com/discuss/channels/laravel/custom-validation-message-for-array-using-different-key?page=0

Override laravel validation message

This is the validation code

$validator = Validator::make($request->all(), [ 
      'first_name' => 'required',
      'last_name' => 'required',
      'email' => 'required|email|unique:users',
      'fcm_token' => 'required',
      'password' => 'required',  
      'c_password' => 'required|same:password' 
    ]); 

This Post Has One Comment

  1. No Fault

    You can manually loop over the error Message Bag and construct the response to replace a key

    $validator = Validator::make($request->all(), [
    ‘first_name’ => ‘required’,
    ‘last_name’ => ‘required’,
    ’email’ => ‘required|email|unique:users’,
    ‘fcm_token’ => ‘required’,
    ‘password’ => ‘required’,
    ‘c_password’ => ‘required|same:password’
    ]);

    $errors = [];
    foreach ($validator->errors()->messages() as $key => $value) {
    if($key == ’email’)
    $key = ‘message’;
    $errors[$key] = is array($value) ? implode(‘,’, $value) : $value;
    //implode is for when you have multiple errors for a same key
    //like email should valid as well as unique
    }

    $result = array(“status” => count($errors)?0:1, ‘data’=>$errors);
    return $result;

Leave a Reply