title: Laravel Scope by pivot data values
body: <p>Say I want to store various bits of data about customers, so I have two models linked by a pivot table, storing the customer's values for each datafield type on the pivot table:</p>
  
  <pre><code>Customer {
      public function datafields()
      {
          return $this-&gt;belongsToMany('Datafield')-&gt;withPivot('value');
      }
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>Datafield {
      public function customers()
      {
          return $this-&gt;belongsToMany('Customer')-&gt;withPivot('value');
      }
  </code></pre>
  
  <p>So my tables are customers, customer_datafield, datafields.</p>
  
  <p>How can I set up a query scope in the customer to find all customers that have a value of x for a specfic datafield?</p>
  
  <p>Something along the lines of</p>
  
  <pre><code>Customer {
      public function datafields()
      {
          return $this-&gt;belongsToMany('Datafield')-&gt;withPivot('value');
      }
      public function scopeSearch($query, $searchfor)
      {
          return $query-&gt;datafields()-&gt;pivot()
              -&gt;where('value', $searchfor)
              -&gt;where('datafield_id', 123);
      }
  }
  </code></pre>
  
  <p>I've tried a few methods but not having any luck geting one to work. Any suggestions much appreciated!</p>