title: How to add a new field to a Model and use it in Eloquent
body: <p>I'm trying the following: I have a model, called Pub, that has the following fields: "id","name","address","longitude","latitude","schedule","photo", etc.</p>
  
  <p>As I need to know the distance between Pub and User, so I've created a function that calculates the distance in Pub Model using longitude and latitude:</p>
  
  <pre><code>public function pubDistance()
  {
      $userLat = '';
      $userLong = '';
  
      $pubLat = $this-&gt;latitude;
      $pubLong = $this-&gt;longitude;
  
      if(!($userLat &amp;&amp; $userLong))
      {
          $userLat = 40.4169473;
          $userLong = -3.7035285;
      }
  
      $earthRadius = 6371;
  
      $latFrom = deg2rad($userLat);
      $lonFrom = deg2rad($userLong);
      $latTo = deg2rad($pubLat);
      $lonTo = deg2rad($pubLong);
  
      $latDelta = $latTo - $latFrom;
      $lonDelta = $lonTo - $lonFrom;
  
      $a = pow(cos($latTo) * sin($lonDelta), 2) +
          pow(cos($latFrom) * sin($latTo) - sin($latFrom) * cos($latTo) * cos($lonDelta), 2);
  
      $b = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($lonDelta);
  
      $angle = atan2(sqrt($a), $b);
  
      $distance = round($angle * $earthRadius, 2);
  
      return $distance;
  
  }
  </code></pre>
  
  <p>And I use this function here (inside Pub model too):</p>
  
  <pre><code>public function getPubDistanceToUserAttribute()
  {
      return $this-&gt;pubDistance();
  }
  </code></pre>
  
  <p>Then the problem I have is how to add the field to Pub model and use to order my pubs by distance.</p>
  
  <p>The first thing I could do it appending: </p>
  
  <pre><code>protected $appends = ['pub_distance_to_user'];
  </code></pre>
  
  <p>But I'm having problems in my controller to order by that new field:</p>
  
  <pre><code>public function getPubs()
  {
      $pubs = Pub::all();
  
      return $pubs;
  }
  </code></pre>
  
  <p>This is what I have:</p>
  
  <pre><code>{
  "id": 1,
  "name": "Dr. Nikko Braun",
  "address": "453 Wyman Crossroad\nSouth Eliashaven, NY 75636",
  "longitude": "118.9395890",
  "latitude": "-62.3235600",
  "schedule": "1986-11-13 10:15:48",
  "photo": 
  "email": "sylvester.rutherford@example.net",
  "phone": "1-841-349-8925 x684",
  "pub_distance_to_user": 15556.09
  </code></pre>
  
  <p>}</p>
  
  <p>How I could use accesors and mutators here, or something like this in this case?...</p>
  
  <p>Thanks a lot!!</p>