I'm building my first React JS system and utilising Laravel Passport for my authentication stuff. I have it working really well up until I try and submit invalid data. When I send my post request, I have the following Request class set up:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegisterUser extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|confirmed|min:8'
];
}
}
Which is triggered from the /api/register end point seen in the following React JS method:
registrationHandler = e => {
e.preventDefault();
$("#email-login-btn")
.attr("disabled", "disabled")
.html(
'<i class="fas fa-spinner fa-spin fa-1x fa-fw"></i><span class="sr-only">Loading...</span>'
);
var formData = new FormData();
formData.append("email", e.target.elements.email.value);
formData.append("name", e.target.elements.name.value);
formData.append("password", e.target.elements.password.value);
formData.append(
"password_confirmation",
e.target.elements.password_confirmation.value
);
axios
.post("/api/register", formData)
.then(response => {
return response;
})
.then(json => {
if (json.status == 201) {
const MySwal = withReactContent(
Swal.mixin({
toast: true,
position: "top-end",
showConfirmButton: false,
timer: 3000
})
);
MySwal.fire({
type: "success",
title: "Registered successfully"
});
} else {
$("#email-login-btn")
.removeAttr("disabled")
.html("Register");
}
})
.catch(error => {
console.log(error.response.data.errors);
$("#email-login-btn")
.removeAttr("disabled")
.html("Register");
});
};
You can see that at the bottom I'm trying to catch the errors and log them to the console with console.log(error.response.data.errors); - this works great, I can see them in the console like this:
My controller method is this, nothing crazy:
{
// If validation hasn't failed, register the user
User::create([
'name' => request('name'),
'email' => request('email'),
'password' => bcrypt(request('password'))
]);
return response()->json(['status' => 201]);
}
But what I'm trying to do now is show the errors on the register page, under my form. I've tried setting the errors inside the state (where I'm doing the console log) and then pass them as props to my Register.js file, but it always returns "undefined", presumably because the routes aren't changing.
Is there a better way to display the errors that the system sends back? I'm at a bit of a loss with this currently.
Thanks!

