0

I'm new to Laravel. I'm trying to create an API post request. This is the validation I have.

    $request->validate([
        'name' => 'required',
        'phone' => 'required',
        'address' => 'required',
        'started_date' => 'required|after:2012-01-01|before:tomorrow',
    ]);

When the validation fails, with the validation I have, let's say "name" and "started_date" are missing, this is the response I get.

{
 "message": "The given data was invalid.",
 "errors": {
    "name": [
        "The name field is required."
    ],
    "started_date": [
        "The started date must be a date before tomorrow."
    ]
}

However, It's not the format I want. Here is what I want

 {
 "message": "The given data was invalid.",
 "errors": {
    "name": "The name field is required.",
    "started_date": "The started date must be a date before tomorrow."
}

So what should I do to format the response?

4
  • 2
    Did you think about why the structure above exists? What are you going to do if an attribute has multiple errors like this: "name": [ "The name field is required.","Some other error.","Another one", ], now you cannot simply do the desired transformation. Please explain why you want it to look diffrent? Commented Aug 2, 2020 at 14:59
  • I think the structure above exists beacuse, for example, name can have multiple conditions. I want it to look differrent because it will make it easy for the front-end app. I don't think I need to show multiple error messages Commented Aug 2, 2020 at 15:18
  • Just use the first element in the array? errors.name[0] Commented Aug 3, 2020 at 4:58
  • I think this can be an option to go with Commented Aug 3, 2020 at 15:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.