What causes the data validation error in this Laravel API?(是什么原因导致此Laravel API中的数据验证错误?)
本文介绍了是什么原因导致此Laravel API中的数据验证错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Laravel 8和Vue 3制作注册表。后端是API。
在users
表迁移文件中,我有:
class CreateUsersTable extends Migration {
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->unsignedInteger('country_id')->nullable();
$table->foreign('country_id')->references('id')->on('countries');
$table->rememberToken();
$table->timestamps();
});
}
// More code here
}
如上所述,countries
表中的ID是users
表中的外键。
我在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_id' => 'required|exists:countries',
'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_id.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_id' => $fields['country_id']
]);
$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_id: null,
},
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">×</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_id">
<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>
问题
由于我无法确定的原因,应用程序在浏览器(网络选项卡)中抛出此错误,状态代码为422无法处理的内容:
给定数据无效
问题
我做错了什么?
推荐答案
country_id
字段将不存在于countries
表中。默认情况下,Laravel将按要验证的字段的名称在数据库中查找列。因此,您应该使用此命令:
'country_id' => 'required|exists:countries,id'
https://laravel.com/docs/8.x/validation#specifying-a-custom-column-name
这篇关于是什么原因导致此Laravel API中的数据验证错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:是什么原因导致此Laravel API中的数据验证错误?
基础教程推荐
猜你喜欢
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01