2016-12-03 56 views
0

我如何驗證表,如果privacy = public,那麼所有用戶都有唯一的標題,但privacy = private,那麼每個用戶都有一個唯一的標題。Laravel中的條件驗證

--------------------------- 
user_id | title | privacy 
--------------------------- 
    2 | hello | public 
--------------------------- 
    2 | hello | private 
--------------------------- 
    2 | hello | private **Error** 
--------------------------- 
    2 | hello | public **Error** 
--------------------------- 
    3 | hello | public **Error** 
--------------------------- 
    3 | hello | private 
--------------------------- 
+0

你可以把關於你到底做了什麼的代碼? –

回答

0

嘿,我可以有很多的嘗試! 感謝後解決我的問題大家誰幫助我,或建議我

大多喜歡我自己的解決方案

 'title' => Rule::unique('galleries')->where(function ($query) 
     { 
      if($this->input('privacy')=='private') 
      { 
       $query->where([['privacy','=','private'],['user_id','=',Auth::user()->id]]); 
      } 
      else 
       $query->where('privacy', '=','public'); 

     }), 

希望這是最簡單的解決方案

1

可能是,如果你想驗證自己來執行,你可以使用這個庫

網址:https://github.com/felixkiss/uniquewith-validator

替代的解決方案:

if($request->privacy == "private"){ 
    $count = DB::table('your_table_name') 
       ->where('title','=',$request->title) 
       ->where('user_id','=,$request->user_id) 
       ->count(); 
    if($count >0){ 
     return "You error message for privacy private" 
    } 
}else{ 
    $count = DB::table('your_table_name') 
       ->where('title','=',$request->title) 
       ->count(); 
    if($count >0){ 
     return "You error message for privacy public" 
    } 

} 

的希望,所以你明白這個簡單的代碼。詢問是否有疑問。

+0

有沒有辦法在laravel中使用默認驗證系統 –

1

你需要爲這個自定義驗證,這基本上將使用內置的基於隱私的條件獨特的規則:

class CustomValidator extends Illuminate\Validation\Validator 
{ 
    public function validateUniqueIfPrivacy($attribute, $value, $parameters) { 

     $privacyValue = array_get($validator->getData(), 'privacy_field'); 

     if ($privacyValue == 'private') { 
     return $isTitleUniqueForUser = $this->validateUnique($attribute, $value, 'my_table', 'title', NULL, 'user_id', $parameters[0]); 
     } else { 
     return $isTitleUniqueForAll = $this->validateUnique($attribute, $value, 'my_table', 'title'); 
     } 

    } 
} 

您已經註冊了自定義的驗證和自動加載它的類後,您可以這樣使用它,是,只透過$userId作爲參數:

$rules = array(
     'title' => 'unique_if_privacy:,' . $user->id, 
); 

有關如何實現自定義驗證更多信息:Laravel 4.2 documentation(也可用於Laravel 5)