我有一个App,我希望表中的三个字段:rollyear
,rollfaculty
和rollno
的组合是唯一的。为此,我在迁移文件中执行了以下操作:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->string('rollyear');
$table->string('rollfaculty');
$table->string('rollno');
$table->unique(['rollyear','rollfaculty','rollno']);
});
这可以按预期工作,但是每当将重复的值提供给指定字段时,我就会收到整页的违反完整性约束错误。
如何处理此错误并向用户提供简化的错误消息,如下图所示?
答案 0 :(得分:0)
通过jQuery添加验证
将此文件保存在public / js文件夹中
这里是a link!
并投放另一个用于注册的验证文件
// validate signup form on keyup and submit
$("#addUserForm").validate({
rules: {
name:{
required:true
},
email: {
required: true,
email: true,
remote: {
url: "/checkuser",
type: "get"
}
},
password: {
required: true,
minlength: 5
},
image: {
required:true,
accept: "jpg|jpeg|png|JPG|JPEG|PNG"
}
},
messages: {
name: {
required:"Please enter a name"
},
email: {
required:"Please enter a email address",
email:"Please enter a valid email address",
remote:"Email Already Exist"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
image: {
required: "Please provide a profile image",
accept: "Please upload only jpg,jpeg,png"
}
}
});
添加/ checkuser
public function checkUser()
{
$user = User::where('email', request('email'))->exists();
if($user){
return 'false';
}
else {
return 'true';
}
}
答案 1 :(得分:0)
请在存储用户详细信息的控制器中放置以下代码。
$chkUniqueEmailId = DB::table('users')->where('email', '=', $request->email)->first();
if(!empty($chkUniqueEmailId)){
return redirect()->route('auth.register')->withFlashDanger("This email address already exists.");
}