title: Conditional wherehas with Laravel Eloquent
body: <p>I have one similar (<code>area</code>) value in two tables <code>one</code> and <code>two</code> and these two tables has relation with main table <code>master</code>. At a time, the <code>master</code> table will be having data in one relation only and the other one will be <code>null</code>.</p>
  
  <p>With this architecture, I have a search page where user can search any values related to these tables and the search fields are placed with <code>AND</code> condition.</p>
  
  <p>Here, if user enters some value for <code>area</code> I need to check the area value exists in any one of the tables (<code>one</code> or <code>two</code>) without breaking the <code>AND</code> condition. Tried the below code but it is breaking <code>AND</code> rule and considering <code>OR</code>. Any suggestions to fix?</p>
  
  <pre><code>$result =  Master::where(function ($query) use ($request) {
      if ($request-&gt;filter == true) {
          $query-&gt;where('user_id', Auth::user()-&gt;id);
      }
      // other conditions here
      if (!empty($request-&gt;area_from) &amp;&amp; !empty($request-&gt;area_to)) {
          $query-&gt;whereHas('one', function ($query) use ($request) {
              $query-&gt;whereBetween('area', [$request-&gt;area_from, $request-&gt;area_to]);
          });
          $query-&gt;orWhereHas('two', function ($query) use ($request) {
              $query-&gt;whereBetween('area', [$request-&gt;area_from, $request-&gt;area_to]);
          });
      }
      // other conditions here
  
  })-&gt;with(['one', 'two'])-&gt;paginate($request-&gt;item);
  </code></pre>