Search code examples
laravellaravel-5.3laravel-validation

Conditional validation in Laravel


How i validate the table, if privacy=public then all user has unique title but privacy=private then every single user has a unique title.

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

Solution

  • Hey i can solve my question after a lot of try!, Thanks Everyone who help me or suggest me

    Mostly like my own solution

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

    Hopefully this is the most easy solution