0
votes

If I validate my frontend form with axios by using the 'data' option it fails the validation in my backend laravel application.

axios.post('http://example.com/', {
  'Content-Type': 'multipart/form-data',
  Accept: 'application/json',
  data: {
      email: 'email@email.com',
      password: '12345678',
    }
}).then(res => console.log(res))
  .catch(err => console.log(err));

So here I use the 'data' option to validate.

$request->validate([
        'email' => 'required|string|email',
        'password' => 'required|string'
]);

Returns: 422 email is required password is required.

This is how the request gets formatted:

{Content-Type: "application/json", data: {email: "email@email.com", password: "12345678"}}

However if I submit the form this way with axios it validates and I'm logged in:

'Content-Type': 'multipart/form-data',
'Accept': 'application/json',
'email': 'email@email.com',
'password': '12345678',

So my question is how to tell the validater to look inside the data object?

EDIT 1: As requested dd($request->attributes); returns:

ParameterBag {#53
  #parameters: []
}
2

2 Answers

2
votes

This is because you are adding headers as data in your axios request. your request should be like this:

const headers = {
    'Accept': "application/json",
    'Content-Type': "application/json",
};

let data: {
      email: 'email@email.com',
      password: '12345678',
    };

axios.post('http://example.com/',data, {headers:headers})
            .then( (response) => {
                //do the stuff
            })
            .catch( (error) => {
                // do the stuff
            });

Note: axios post function takes first argument as url, second as data and third as config (headers etc) while in your case you are mixing the header with data. you can read more about axios here

Thanks.

0
votes

The problem is, why would you need to add data in your axios?

If you're add data, then your validation should be as such:

$request->validate([
    'data.email' => 'required|string|email',
    'data.password' => 'required|string',
]);