我在使用已插入的电子邮件提交注册表单时收到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']);
答案 0 :(得分:1)
更改此规则
'email' => 'required|between:3,64|email'
到这个
'email' => 'required|between:3,64|email|unique:users'
答案 1 :(得分:0)
只更新您的规则:
$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
此致