Laravel 4:避免重复输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18572994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:22:20  来源:igfitidea点击:

Laravel 4: avoid duplicate entry

laravelduplicateslaravel-4newsletter

提问by FrancescoMussi

In my app there is a simple form with one field (email) that give the possibility to register to the newsletter.

在我的应用程序中,有一个带有一个字段(电子邮件)的简单表单,可以让您注册时事通讯。

If i entry a new email, all it works fine. If i entry an email that already exists in the database i get the error SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry... Because i had defined that field as unique in the database.

如果我输入新电子邮件,一切正常。如果我输入数据库中已存在的电子邮件,我会收到错误 SQLSTATE[23000]: Integrity constraint conflict: 1062 Duplicate entry... 因为我已将该字段定义为数据库中的唯一字段。

All i want to do is to redirect::back()->with('message', 'email already registered') But i do not know how can i do this? I can just put an if statement in the method controller? Or i have to define it in $rules in the model, adding another rule:

我想要做的就是重定向::back()->with('message', 'email already registered') 但我不知道我该怎么做?我可以在方法控制器中放置一个 if 语句吗?或者我必须在模型中的 $rules 中定义它,添加另一个规则:

public static $rules = array(
    'email' => 'required',);

Thank you!

谢谢!

采纳答案by Laurence

Just define a unique ruleon your users table:

只需在您的用户表上定义一个唯一规则

public static $rules = array(
    'email' => 'required|unique:users|email');