title: how to validate unique combination of two fields in Laravel?
body: <p>I am trying to add validation constraints on the registration of a new user and I want the combination of two fields be unique in the database. The error that i get is from the database saying i have a integrity constraint violation. the table I have is called users and the fields i want to have unique combination are called ssn and lastfour.</p>
  
  <p>I added the line $table->unique(array('ssn','lastfour')); in the user migration and I also added some fields in the registration which work fine and the database is ok. I tried the solution in a similar question posted about 9 months ago <a href="https://stackoverflow.com/questions/50349775/laravel-unique-validation-on-multiple-columns?fbclid=IwAR11pAX9BfNsEpLBfXGb3YtDFgO9NzYD055fxg5o037eMu3xLznedQLcH5Y">Laravel unique validation on multiple columns</a> but i get undefined variable on line "Rule::unique('servers')->where(function ($query) use($ssn,$lastfour)"</p>
  
  <pre><code>protected function validator(array $data)
  {
      return Validator::make($data, [
          'name' =&gt; ['required', 'string', 'max:255'],
          'lastname' =&gt; ['required', 'string', 'max:255'],
          'username' =&gt; ['required', 'string', 'max:255', 'unique:users'],
          'ssn' =&gt; ['required', 'string', 'regex:/^[0-9]*$/','max:8', 'min:8'],
          'lastfour' =&gt; ['required', 'string', 'regex:/^[0-9]*$/','max:4', 'min:4'],
          'email' =&gt; ['required', 'string', 'email', 'max:255', 'unique:users'],
          'password' =&gt; ['required', 'string', 'min:6', 'confirmed'],
      ]);
  }
  </code></pre>
  
  <p>i tried the following code</p>
  
  <pre><code>'lastfour' =&gt; ['required', 'string', 'regex:/^[0-9]*$/','max:4', 'min:4', 
                          Rule::unique('users')-&gt;where(function ($query) use 
                          ($ssn, $lastfour){
                              return $query-&gt;where('ssn', $ssn)
                              -&gt;where('lastfour', $lastfour);
                          })
          ],
  </code></pre>