2014-07-25 148 views
0

我在Laravel非常新,這是我在Laravel的第一個項目。像往常一樣,首先我正在開發一個完整的用戶身份驗證系統。我可以註冊一個單用戶,可以發送用戶驗證郵件,點擊該鏈接後,我可以激活一個新的用戶帳戶,可以登錄,並可以註銷。但之後,當我試圖註冊另一個新用戶和點擊驗證鏈接後,我現在面臨一個例外是,Laravel SQLSTATE [23000]:完整性約束違規:1062重複條目

Illuminate \ Database \ QueryException 
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key  'users_code_unique' (SQL: update `users` set `code` = , `active` = 1, `updated_at` = 2014-07- 25 04:26:06 where `id` = 41) 

現在這是我的route.php,

<?php 

Route::get('/',array(
    'as' =>'home', 
    'uses' =>'[email protected]' 
    )); 

Route::get('/signin',array(
    'as'  =>'signin', 
    'uses'  =>'[email protected]' 
    )); 

Route::get('/signup',array(
    'as' => 'signup', 
    'uses' => '[email protected]' 
    )); 

/* 

/* 
/Authenticated Group 
*/ 
Route::group(array('before' => 'auth'),function(){ 
/* 
/Sign Out(GET) 
*/ 

Route::get('/signout',array 
    (
     'as' => 'signout', 
     'uses' => '[email protected]' 
    )); 

}); 

/* 
/UnAuthenticated Group 
*/ 
Route::group(array('before' => 'guest'),function(){ 

/* CSRF Protect*/ 
Route::group(array('before' => 'csrf'),function(){ 
     /* 
     /Create Account(POST) 
     */ 
     Route::post('/signup',array(
       'as'=> 'signup', 
       'uses'=>'[email protected]' 
      )); 

     /* 
     /Sign In(POST) 
     */ 

     Route::post('/signin',array(
       'as' => 'signin-post', 
       'uses' => '[email protected]' 
      )); 
}); 

/* 
/Sign In (GET) 
*/ 

Route::get('/signin',array(
     'as' => 'signin', 
     'uses' => '[email protected]' 
    )); 

/* 
/Create Account(GET) 
*/ 
Route::get('/signup',array(
     'as' => 'signup', 
     'uses'=> '[email protected]' 
    )); 
Route::get('signup/account/activate/{code}',array(
     'as'  =>'activate-account', 
     'uses'  =>'[email protected]' 
    )); 
}); 
?> 

,這是我的AccountController

<?php 

class AccountController extends \BaseController { 

public function signinGet() 
{ 
    return View::make('account.signin'); 
} 

public function signinPost(){ 

    $validator = Validator::make(Input::all(),array(
      'email' => 'required|email', 
      'password' => 'required' 
     )); 

    if($validator->fails()){ 
     //redirect to the signin page 
     return Redirect::route('signin') 
       ->withErrors($validator) 
       ->withInput(); 
    }else{ 
     //Attempt user singin 

     $auth = Auth::attempt(array 
      (
       'email' => Input::get('email'), 
       'password' => Input::get('password'), 
       'active' => 1 
      )); 

     if($auth){ 
      //Redirect To intented URL 
      return Redirect::intended('/'); 
     } 
     else 
     { 

      return Redirect::route('signin') 
           ->with('global','The username or password you provided is wrong or account not activated!'); 
     } 

    } 

      return Redirect::route('signin')  
           ->with('global','There is a problem Signing You in.'); 
} 


/** 
* Show the form for creating a new resource. 
* 
* @return Response 
*/ 

public function signupGet() 
{ 
    return View::make('account.signup'); 
} 

public function signupPost() 
{ 
    $validator = Validator::make(Input::all(), array(

     'email'    => 'required|max:255|email|unique:users', 
     'username'   => 'required|min:3|unique:users', 
     'password'   => 'required|min:6', 
     'password_again' => 'required|same:password' 

     ) 
    ); 

    if($validator->fails()) 
    { 
     return Redirect::route('signup') 
      ->withErrors($validator) 
      ->withInput(); 
    }else 
    { 
     $email   = Input::get('email'); 
     $username  = Input::get('username'); 
     $password  = Input::get('password'); 

     //Activation Code 
     $code = str_random(60); 

     $user = User::create(array(
        'email'  => $email, 
        'username' => $username, 
        'password' => Hash::make($password), 
        'code'  => $code, 
        'active' => 0     
        ) 
     ); 

     if($user){ 
      //User Activation Code Creation 
      Mail::send('emails.auth.activate', array('link' => URL::route('activate-account',$code), 'username' => $username),function($message) use ($user) 
       { 
        $message->to($user->email,$user->username)->subject('Activate Your Account'); 
       }); 

      return Redirect::route('signup') 
          ->with('global','Your Account has been created! We have sent you an email to activate your account.Please Check the both the Inbox and Spam Folder.'); 

     } 

    } 


    //return 'This is a Post Result'; 
} 

public function activatePost($code){ 

    $user = User::where('code','=',$code)->where('active','=',0); 
    if($user->count()){ 
     $user = $user->first(); 

     $user->active = 1; 
     $user->code = ''; 
     if($user->save()){ 
      return Redirect::route('home') 
          ->with('global','Activated!.You can sign in now!'); 
     } 
    } 

    else{ 
     return Redirect::route('signup') 
         ->with('global','Sorry!We could not activate your acount,please try again later.'); 
    } 
} 


public function signoutGet(){ 

    Auth::logout(); 
    return Redirect::route('home'); 
} 
} 
?> 

,這是我創建的用戶遷移文件

<?php 

use Illuminate\Database\Schema\Blueprint; 
use Illuminate\Database\Migrations\Migration; 

class CreateUsersTable extends Migration { 

public function up() 
{ 
    Schema::create('users', function(Blueprint $table) 
    { 
     $table->increments('id'); 
     $table->string('username',255)->unique(); 
     $table->string('email',255)->unique(); 
     $table->string('password',60); 
     $table->string('password_temp',60); 
     $table->string('code',60)->unique(); 
     $table->integer('active'); 
     $table->timestamps(); 
    }); 
} 

/** 
* Reverse the migrations. 
* 
* @return void 
*/ 
public function down() 
{ 
    Schema::drop('users'); 
} 

} 
?> 

,這是我user.php的

<?php 

use Illuminate\Auth\UserTrait; 
use Illuminate\Auth\UserInterface; 
use Illuminate\Auth\Reminders\RemindableTrait; 
use Illuminate\Auth\Reminders\RemindableInterface; 

class User extends Eloquent implements UserInterface, RemindableInterface { 


    public function getRememberToken() 
    { 
     return $this->remember_token; 
    } 

    public function setRememberToken($value) 
    { 
     $this->remember_token = $value; 
    } 

    public function getRememberTokenName() 
    { 
     return 'remember_token'; 
    } 

protected $fillable = array('email','username','password','password_temp','code','active'); 

use UserTrait, RemindableTrait; 

/** 
* The database table used by the model. 
* 
* @var string 
*/ 
protected $table = 'users'; 



/** 
* The attributes excluded from the model's JSON form. 
* 
* @var array 
*/ 
protected $hidden = array('password', 'remember_token'); 

} 
?> 

現在什麼問題呢?

+0

它看起來像'用戶> code'不是唯一的。你確定它是?試着迴應它,並與你已經在數據庫中得到的結果進行比較。我在winXP上用str_random遇到了一個問題 - 在短時間內它生成了相同的隨機字符串... – Tom

+0

對不起,對我來說,它不是laravels 4'str_random',而是一些其他函數來隨機化,但它產生和我說的一樣。 – Tom

+0

那麼如何解決這個問題,你有什麼解決辦法嗎? – Tanveer

回答

5

確保您codenullable,然後而不是設置它的值以空字符串,使其空:

$code = null; 

然後你就可以將其保存爲NULL(MySQL的),而它仍然是獨一無二的。


也會改變該之一:

$user = User::where('code','=',$code)->where('active','=',0); 
    if($user->count()){ 
    $user = $user->first(); 

要:

$user = User::where('code','=',$code)->where('active','=',0)->first(); 
    if(count($user)){ 

你並不需要調用數據庫兩次,只是檢查,如果返回的結果是不爲空(count會做),這意味着它返回了一個User對象。

+0

我有同樣的問題,我做了$ primarykey ='',它的工作,之後,我只是把$ primarykey放回$ primarykey = null – Supplement

1

我找到了。您已將代碼列設置爲唯一,但您在用戶點擊激活鏈接後將其設置爲空字符串。在表中已經有一行代碼='';所以它會拋出一個錯誤。問題是在這裏(activatePost):

$user->code = ''; 

因此,要麼不清空它,將其設置爲別的東西或設置數據庫列爲不唯一。

我會離開代碼而不清空它,另外我會檢查用戶是否被激活 - activatePost中的簡單if。也許最好不僅要根據代碼驗證用戶,還要在鏈接中使用哈希ID。

0

你需要做一些事情來改善你的代碼。但是,當您將列設置爲唯一併嘗試將相同數據重新插入另一行時,通常會發生重複條目。最讓人困惑的時候是當你檢查你的表並且找到空的列時。吶喊!當列設置爲唯一且爲空時,表示沒有其他列可以包含空數據。

簡而言之,列的形式不能重複,無論是null還是數據。

1

你的問題可以使用驗證器來檢查。只是因爲這樣使用:

use Validator; 
use Request; 
//... 
//unique will pre check the key code weather if unique in tbl_name 
public function yourfunc(Request $request) { 
    // set the rules to check 
    $rules = ['code'=>'required|unique:tbl_name']; 
    $validator = Validator::make($request->all(), $rules); 
    if ($validator->fails()) { 
     // handler errors 
     $erros = $validator->errors(); 
    } 
    //... everything is ok here 
} 

,您可以探索更多的laravel validation

相關問題