我在使用已经插入的电子邮件提交注册表单时收到了2次差错
违反完整性约束:1062密钥users_email_unique的重复条目'test@test.com'
.
SQLSTATE[23000]:违反完整性约束:1062键'users_email_unique'的重复条目'test@test.com'
我有数据库索引users_email_unique导致错误,但我如何处理这样的错误
模型
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable {
protected $table = "users";
protected $fillable = array('first_name', 'last_name', 'password', 'email');
protected $hidden = ['password', 'remember_token'];
public function roles() {
return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
}
public function hasAnyRole($roles) {
if(is_array($roles)) {
foreach($roles as $role) {
if($this->hasRole($role)) {
return true;
}
}
}
else {
if($this->hasRole($roles)) {
return true;
}
}
return false;
}
public function hasRole($role) {
if($this->roles()->where('name', $role)->first()) {
return true;
}
return false;
}
}
控制器
<?php
namespace App\Http\Controllers;
use App\Post;
use App\ContactMessage;
use App\User;
use App\Role;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller {
public function postSignUp(Request $request) {
$rules = [
'first_name' => 'required|min:3|max:80|alpha',
'last_name' => 'required|min:3|max:80|alpha',
'email' => 'required|between:3,64|email',
'password' => 'required|alphaNum|between:4,8|confirmed',
'password_confirmation'=> 'required|alphaNum|between:4,8'
];
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
return Redirect::route('signup')->withErrors($validator)->withInput();
}
$user = new User();
$user->first_name = $request['first_name'];
$user->last_name = $request['last_name'];
$user->email = $request['email'];
$user->password = bcrypt($request['password']);
if($user->save()){dd('aaaaa');
$user->roles()->attach(Role::where('name', 'User')->first());
Auth::login($user);
return redirect()->route('blog.index');
}
else {
dd('sssss');
}
}
}
路线
Route::get('/signup', ['uses' => 'AdminController@getSignUp','as' => 'signup']);
Route::post('/signup', ['uses' => 'AdminController@postSignUp','as' => 'signup']);
改变这条规则
'email' => 'required|between:3,64|email'
到这个
'email' => 'required|between:3,64|email|unique:users'
仅像这样更新您的规则:
$rules = [
'first_name' => 'required|min:3|max:80|alpha',
'last_name' => 'required|min:3|max:80|alpha',
'email' => 'required|between:3,64|email|unique:users',
'password' => 'required|alphaNum|between:4,8|confirmed',
'password_confirmation'=> 'required|alphaNum|between:4,8'
];
您可以在此链接上查看此留档:https://laravel.com/docs/5.2/validation#rule-unique
问候