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

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