2016-07-05 100 views
0

在我的CreateUserRequest for email中,它具有唯一的驗證規則,並且對於我的EditUserRequest也是一樣的,但它一直說這個地址已經被註冊了。如何從規則中的唯一性中排除我正在更新的用戶的電子郵件地址?否則,我必須在每次更新用戶時註冊一個新的電子郵件地址。如何保持唯一驗證Laravel 5.2

EditUserRequest:

namespace App\Http\Requests; 

use App\Http\Requests\Request; 

class EditUserRequest extends Request 
{ 
    /** 
    * Determine if the user is authorized to make this request. 
    * 
    * @return bool 
    */ 
    public function authorize() 
    { 
     return true; 
    } 

    public function messages() 
    { 
     return [ 
      'unique'=>'That email address is already registered', 
      'regex'=>'Password must contain at least 1 letter and 1 number' 
     ]; 
    } 

    /** 
    * Get the validation rules that apply to the request. 
    * 
    * @return array 
    */ 
    public function rules() 
    { 
     return [ 
      'name'=>'required|min:2|max:50', 
      'email'=>'required|email|unique:users,email|max:50' 
      //'password'=>'min:8|regex:/[a-zA-Z][0-9]/' NOT IN USE WHILE IN DE 
     ]; 
    } 
} 

CreateUserRequest:

namespace App\Http\Requests; 

use App\Http\Requests\Request; 

class CreateUserRequest extends Request 
{ 
    /** 
    * Determine if the user is authorized to make this request. 
    * 
    * @return bool 
    */ 
    public function authorize() 
    { 
     return true; 
    } 

    public function messages() 
    { 
     return [ 
      'unique'=>'That email address is already registered', 
      'regex'=>'Password must contain at least 1 letter and 1 number' 
     ]; 
    } 

    /** 
    * Get the validation rules that apply to the request. 
    * 
    * @return array 
    */ 
    public function rules() 
    { 
     return [ 
      'name'=>'required|min:2|max:50', 
      'email'=>'required|email|unique:users,email|max:50', 
      'password'=>'required' 
      //'password'=>'required|min:8|regex:/[a-zA-Z][0-9]/' NOT IN USE WHILE IN DE 
     ]; 
    } 
} 

回答

0

你需要改變你的EditUserRequest並添加當前記錄的ID被忽略。

看看官方文檔: https://laravel.com/docs/5.1/validation#rule-unique 段落:強制一個獨特的規則將其忽略給定的ID

喜歡的東西:

'email'=>'required|email|unique:users,email,'. $user->id .'|max:50' 
+0

如果您沒有依賴注入,則可以使用Request :: input('id')而不是$ user-> id。 –

+0

你也可以使用'request() - > id'。 – user2094178

+0

它說$用戶是未定義的。我如何給規則()訪問$用戶? –

0

所有這一切都需要被添加$user = User::find($this->users);和然後按照建議追加$user->id;。剛剛找不到用戶。