Laravel 中的条件验证

Conditional validation in Laravel

我如何验证 table,如果 privacy=public 那么所有用户都有唯一的标题,但是 privacy=private 那么每个用户都有唯一的标题。

 ---------------------------
 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   
 ---------------------------

如果你想在 Validator 本身中执行,你可以使用这个库

url : 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"
    }

}

希望您能理解这个简单的代码。有疑问请追问

为此你需要一个自定义验证器,它基本上会使用基于隐私条件的内置唯一规则:

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');
      }

   }
}

注册自定义验证器并自动加载其 class 后,您可以像这样使用它,只传递 $userId 作为参数:

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

有关如何实施自定义验证器的更多信息:Laravel 4.2 documentation(也适用于 Laravel 5)

嘿,经过多次尝试,我可以解决我的问题!, 感谢所有帮助我或建议我的人

最喜欢我自己的解决方案

        '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');

        }),

希望这是最简单的解决方案