Within my API, I include the following validation logic:
$request->validate([
'firstname' => 'required',
'lastname' => 'required',
'username' => 'required|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required'
]);
Following that, I handle errors in Axios with the following code:
.catch(error=>{
console.log("Error: " + error.response.data.errors)
})
However, this results in displaying: Error: [object Object]
If I intentionally provide a username that already exists in the database, and then modify the catch block to
.catch(error=>{
console.log("Error: " + error.response.data.errors.username)
})
The output will be Username is already taken
which is desirable.
This poses the challenge of having to explicitly specify
error.response.data.errors.<x error>
to display the message. For instance, if I use data.errors.username
but the email triggers the validation error, the console will show Error: undefined
as there is no data.errors.username
, only data.errors.email
.
Is there a way to access and present the returned error without manual specification? Your assistance is greatly appreciated!