是什么原因导致此Laravel 8和Vue 3应用程序中的验证错误?

2022-03-26 00:00:00 laravel laravel-8 vue.js vuejs3

我正在制作一个由Laravel 8 API和Vue 3前端组成的注册表。

我在AuthController中有这段代码来注册新用户:

class AuthController extends Controller {
    
    public function countries()
    {
        return Country::all('id', 'name', 'code');
    }
    
    public function register(Request $request) {

        $rules = [
            'first_name' => 'required|string',
            'last_name' => 'required|string',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|confirmed',
            'country' => 'required|string',
            'accept' => 'accepted',
        ];

        $customMessages = [
            'first_name.required' => 'First name is required.',
            'last_name.required' => 'Last name is required.',
            'email.required' => 'A valid email is required.',
            'email.email' => 'The email address you provided is not valid.',
            'password.required' => 'A password is required.',
            'password.confirmed' => 'The passwords do NOT match.',
            'country.required' => 'Please choose a country.',
            'accept.accepted' => 'You must accept the terms and conditions.'
        ];

        $fields = $request->validate($rules, $customMessages);
    
        $user = User::create([
            'first_name' => $fields['first_name'],
            'last_name' => $fields['last_name'],
            'email' => $fields['email'],
            'password' => bcrypt($fields['password']),
            'country' => $fields['country']
        ]);

        $token = $user->createToken('secret-token')->plainTextToken;

        $response = [
            'countries' => $this->countries(),
            'user' => $user,
            'token' => $token
        ];

        return response($response, 201);
    }
}

在前端,我有:

const registrationForm = {
  data() {
    return {
      apiUrl: 'http://myapp.test/api',
      formSubmitted: false,
      countries: [],
      fields: {
        first_name: '',
        last_name: '',
        email: '',
        password: '',
        country: '',
      },
      errors: {},
    };
  },
  methods: {
    // get Countries
    async getCountries(){
      try {
        const response = await axios
          .get(`${this.apiUrl}/register`)
          .catch((error) => {
            console.log(error.response.data);
          });

        // Populate countries array
        this.countries = response.data.countries;

      } catch (error) {
        console.log(error);
      }
    },

    registerUser(){
      // Do Registrarion
      axios.post(`${this.apiUrl}/register`, this.fields).then(() =>{
        // Show success message
        this.formSubmitted = true;

        // Clear the fields
        this.fields = {}

      }).catch((error) =>{
        if (error.response.status == 422) {
          this.errors = error.response.data.errors;
        }
      });
    }
  },
  async created() {
    await this.getCountries();
  }
};

Vue.createApp(registrationForm).mount("#myForm");

在VUE模板中:

<form id="myForm">
    <div v-if="formSubmitted" class="alert alert-success alert-dismissible">
      <button type="button" class="close" data-dismiss="alert">&times;</button>
      Your account was created :)
    </div>

    <div class="form-group" :class="{ 'has-error': errors.first_name }">
    <input type="text" class="form-control" placeholder="First name" v-model="fields.first_name">
    <span v-if="errors.first_name" class="error-message">{{ errors.first_name[0] }}</span>
  </div>

  <div class="form-group" :class="{ 'has-error': errors.last_name }">
    <input type="text" class="form-control" placeholder="Last name" v-model="fields.last_name">
    <span v-if="errors.last_name" class="error-message">{{ errors.last_name[0] }}</span>
  </div>

  <div class="form-group" :class="{ 'has-error': errors.email }">
    <input type="email" class="form-control" placeholder="Enter email" v-model="fields.email">
    <span v-if="errors.email" class="error-message">{{ errors.email[0] }}</span>
  </div>

  <div class="form-group" :class="{ 'has-error': errors.password }">
    <input type="password" class="form-control" placeholder="Enter password" v-model="fields.password">
    <span v-if="errors.password" class="error-message">{{ errors.password[0] }}</span>
  </div>

  <div class="form-group" :class="{ 'has-error': errors.password_confirmation }">
    <input type="password" class="form-control" placeholder="Confirm password" v-model="fields.password_confirmation">
    <span v-if="errors.password_confirmation" class="error-message">{{ errors.password_confirmation[0] }}</span>
  </div>

  <div class="form-group">
    <select class="form-control" v-model="fields.country">
       <option value="0">Select your country</option>
       <option v-for="country in countries" :value="country.id">{{ country.name }}</option>
    </select>
  </div>

  <div class="form-group accept pl-1" :class="{ 'has-error': errors.accept }">
    <input type="checkbox" name="accept" v-model="fields.accept">
    <p>I accept <a href="#" class="text-link">The Terms and Conditions</a></p>
    <span v-if="errors && errors.accept" class="error-message">{{ errors.accept[0] }}</span>
  </div>

  <div class="form-group mb-0">
    <button @click.prevent="registerUser" type="submit" class="btn btn-sm btn-success btn-block">Register</button>
  </div>
</form>

问题

由于我无法确定的原因,应用程序在浏览器中抛出此错误:

给定的数据无效。

问题

我做错了什么?


解决方案

我看到的问题是您正在发送country.id(这是正确的),但是您要求string在您的验证上(这是不正确的),国家/地区的验证应该是:

'country' => 'required|exists:countries,id',

exists文档。

并记住随后要检查您是要将country作为string字段存储在数据库(User模型)中,还是应该将其存储为关系。

相关文章