title: Calculate coordinate distance in Laravel
body: <p>I have a scope in my model which creates an alias and I need to execute a where on it, I understand that MySql dose not allow this. </p>
  
  <blockquote>
    <p>Standard SQL doesn't allow you to refer to a column alias in a WHERE
    clause. This restriction is imposed because when the WHERE code is
    executed, the column value may not yet be determined.</p>
  </blockquote>
  
  <p>However, I'm wondering if there is a possible laravel work around? 
  My scope creates an alias distance and I want to check the distance.</p>
  
  <pre><code>public static function scopeDistance($query, $lat, $long)
  {
      return $query-&gt;select(array('*',\DB::raw('( 3959 * acos( cos( radians(' . $lat . ') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(' . $long . ') ) + sin( radians(' . $lat .') ) * sin( radians(latitude) ) ) ) AS distance')));
  } 
  </code></pre>
  
  <p><strong>In my controller:</strong> </p>
  
  <pre><code>\App\Profile::distance($latitude, $longitude)-&gt;where('distance', '&lt;', 50);
  </code></pre>