Converting Laravel Custom Error Validation JSON Response to an Array

I am currently working on developing an API for a registration form and running into an issue with the error format. While the validator correctly displays errors in an object format, I require the JSON response in an array format.

$validator = Validator::make($request->all(), [ 
    'name' => 'required', 
    'mobile' => 'required', 
    'address' => 'required', 
]);
if ($validator->fails()) { 
    return response()->json(['error'=>$validator->errors()], 401);            
}

Current output is

 {
    "error": {
        "name": [
            "The name field is required."
        ],
        "mobile": [
            "The mobile field is required."
        ],
        "address": [
            "The addressfield is required."
        ]
    }
}

Expected output

{
  "error": [
      "The name field is required.",
      "The mobile field is required.",
      "The address field is required."
  ]
}

Answer №1

The correct solution can be found below:

$errors = [];

foreach ($validator->errors()->toArray() as $error)  {
    foreach($error as $sub_error){
        array_push($errors, $sub_error);
    }
}
return ['errors'=>$errors];

The nested loop is necessary because there may be multiple validation conditions that fail for an input (e.g. password is too short and too weak).

In addition, it is important to note that Mayank Pandeyz's answer using a for loop will not iterate without adding toArray() at the end of $validator->errors().

Answer №2

To achieve the desired outcome, it is necessary to loop through the $validator->errors() using a foreach() statement and store each value in an array. Finally, return this array as follows:

$errorArray = array();
foreach ($validator->errors() as $errorMsg)
{
    array_push($errorArray, $errorMsg);
}

return response()->json(['errors'=>$errorArray], 401);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain sub-elements from deeply nested JSON structures

I have a JSON string with the following structure: "total": 5, "filtered": 5, "items": [ { "assignedProducts": [ "antivirus" ], "cloned": false, "device_encryption_status_unmanaged": false, "java_id": "2408cf5b-669c-434e-ac4c-a08d93c40e6a" ...

Is it possible to increase the thumbnail size through the YouTube API?

I am currently leveraging the YouTube API to fetch thumbnails. After inspecting, I have found that all thumbnails are sized at 90 × 120 pixels. Is there a method to retrieve them in larger dimensions? My approach involves using PHP 5.3 and SimpleX ...

Exploring multiple arrays with nested loops using the JOLT library

Within my input data, there is a list of individuals. Each individual has multiple addresses and roles on the contract. For example : Individual #001 has : two addresses - secondary residence and tax address ; two roles - co-subscriber and insured Indi ...

Transferring API information into a nested array and displaying the outcome

Currently, I am utilizing an API to fetch an array of users from which I sort them and collect those with a personalTrainerId matching my userId into an array. The ultimate goal is to render these users as cards on the interface. The desired format for th ...

Transform an HTML table string into JSON format

I discovered a useful library called table to JSON that allows me to convert an HTML Table to JSON using its ID (#testtable in the example below): var table = $('#testtable').tableToJSON(); alert(JSON.stringify(table)); However, I am interested ...

Obtaining a specific section of text based on varying input values

Within a database, I have various requests that include the name of an image in the format of a .jpg file. The length of the image name can vary, so I am avoiding using substr() to extract it. An example value is "Added 545_4.jpg to Photo Album, The Briti ...

Displaying a loading indicator while a file is downloading and the page is being

Is there a way to show a loading indicator while a PDF is being generated in PHP? I redirect to a separate page for the PDF generation process, but the original page stays open and simply downloads the file once it's ready. How can I make a loading in ...

Implementing an alert box upon redirect with PHP

This question is pretty straightforward. I have a form on my index.html page and PHP code to submit that form to an external URL, then redirect back to the index: <?php Echo "<style>body{background:#3e4744}</style>"; Echo "<style>h2{ ...

Calculate the straight line path between points A and B using latitude and longitude coordinates. Determine if a given point is within a certain distance from

After struggling with this problem for a couple of days, I still haven't found a solution :( There is a route on the map from point A to point B in a straight line. Both points have latitude and longitude coordinates. My goal is to determine if point ...

Passing JSON data from template to view in Django

I'm facing an issue with sending JSON data via AJAX from the template to the view and storing it directly in the database. The problem lies in the data not reaching the view successfully. When I try to insert my JSON data (json_data['x'], js ...

What is the process for assigning a name and value to a DOMNode in PHP?

The `DOMNode` class includes the attributes `nodeName` and `nodeValue`, but lacks setters for them. It's possible to directly access the public attribute `nodeValue`, but how can one set the read-only `nodeName`? ...

Understanding JSON in R by extracting keys and values

I have a JSON URL that I need to parse in R. The URL is https://{{API_HOST}}/api/dd/new and contains both keys and values. I can easily parse this JSON in Postman by using the keys and values in the Headers section. Now, I am looking for a way to achieve t ...

Get JSON or partial HTML responses from ASP.NET MVC controller actions

Is there a recommended method for creating controller actions that can return either JSON or partial HTML based on a specified parameter? I'm looking for the optimal way to asynchronously retrieve the results in an MVC page. ...

real-time parsing of JSON responses using PHP

I am currently conducting research for my graduate program in finance on the topic of crypto currencies such as bitcoin. I am focusing on extracting individual data from JSON responses provided by the cryptsy API, which is a platform for trading crypto cur ...

Add a product to your shopping cart in Opencart with the help of Ajax manually

My goal is to automatically add a product to the cart when a user clicks on a button using a custom function that I created. Here is the code for the button: <input type="button" value="Add to cart" onclick="addItemsToCart(83); " class="button btn-suc ...

Invalid parameters passed to JSON_TABLE

I need to extract json data from a row in one of my tables and programmatically select it into another table. Currently, I am only able to do this when I manually provide the raw json data. Here is what I have done so far: SELECT attribute_name, a ...

What is the best way to embed HTML code within an amp-list component?

I was working with a json file that looked like this: { items: [ { FullImage: "87acaed5c90d.jpg", Title: "sometext", description: "<p id="imagenews"><img src='something'></p>" , } ] } I wanted ...

Why do we use array[] instead of just array when creating a new stdClass object?

$arr = []; $arr[] = new stdClass; //this adds an object to the array $arr = new stdClass; //this changes arr into an object It's peculiar because $arr was initially declared as an array. If you remove the brackets in $arr = new stdClass; then $arr ...

The confirmation dialogue is malfunctioning

Need some assistance with my code. I have a table where data can be deleted, but there's an issue with the dialog box that pops up when trying to delete an item. Even if I press cancel, it still deletes the item. Here is the relevant code snippet: ec ...

What is the best way to send multiple id values with the same classname as an array to the database via AJAX in Codeigniter?

Hey everyone, I'm facing an issue where I need to send multiple IDs with the same class name but different ID values to the database using AJAX. However, when I try to do this, only the first value is being picked up and not all of them. How can I suc ...