if you want this kind of validation error message format, I think you should build something a little bit more "complex" of what actually you have out of the box.
Here's what you get with a simple validation test.
This is the code I used.
Route::get('/', function () {
$data = ['name' => ''];
$rules = ['name' => 'required'];
$v = \Validator::make($data, $rules);
dd($v->errors());
});
... and that's the output.
MessageBag {#145 ▼
#messages: array:1 [▼
"name" => array:1 [▼
0 => "The name field is required."
]
]
#format: ":message"
}
"Ok, so what I could do?"
First of all, some assumptions. I see that you're taking only the first error. So, you would get something like this:
"The name field is required."
Working this way, you lose the "name" information. All you have is a simple string message. Not a big deal, considering what you want to achieve.
So, I would work different. There are many ways to do what I'm going to do, I will just show you a procedure.
First of all, let's take the first element of the array.
$errors = $v->errors();
$firstElement = reset($errors);
dd($firstElement);
I will get something like this:
array:1 [▼
"name" => array:1 [▼
0 => "The name field is required."
]
]
Now, starting from this you could do something like
$key = key($firstElement);
$value = reset($firstElement)[0];
To get the key and the value.
Finally, you should use them to build your response.
Here's an example:
return response()->json(
[
"code" => "400",
"error" =>
[
"code" => "10",
"title"=> "Field $key is empty." ,
"message" => $value
]
]);
Obviously I suggest you to create a class to implement the entire mechanism, in order to isolate responsibilities.
Hope it helps.
return response()->json(["code" => "400", "error" => ["code" => "10", "title"=> $message ,"message" => $rules]]);