Laravel 4: avoid duplicate entry

梦想与她 提交于 2019-12-23 12:29:19

问题


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.

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:

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

Thank you!


回答1:


Just define a unique rule on your users table:

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


来源:https://stackoverflow.com/questions/18572994/laravel-4-avoid-duplicate-entry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!