title: Laravel - How to sort, order appended fields
body: <p>I'm creating a function to search books in specific genre. Everything works fine except sorting, ordering by 'stars' which is appended in model.</p>
  
  <p>Function:</p>
  
  <pre><code> $genre = Genre::find($genre_id);
  
  
      $phrase = $request-&gt;search;
      $sort = $request-&gt;sort;
      $order = $request['order'];
  
  
      if (!isset($sort) || !in_array($sort, ['title', 'stars', 'created_at', 'author_id']))
          $sort = 'title';
  
      if (!isset($order) || !in_array($order, ['DESC', 'ASC']))
          $order = 'DESC';
  
  
      $result['name'] = $genre-&gt;name;
      $result['results'] = Book::with('authors')-&gt;whereGenre_id($genre_id)-&gt;where('club_id', '=', $club_id)
          -&gt;where(function ($query) use ($phrase, $club_id, $sort, $order, $user) {
  
              if (isset($phrase))
                  $query-&gt;where('title', 'LIKE', '%' . $phrase . '%');
          })
          -&gt;orderBy($sort, $order)
          -&gt;get();
  </code></pre>
  
  <p>When I try to sort by 'stars' I get an error:</p>
  
  <blockquote>
    <p>Column not found: 1054 Unknown column 'stars' in 'order clause' (SQL:
    select * from <code>books</code> where <code>genre_id</code> = 1 and <code>club_id</code> = 24 and
    <code>books</code>.<code>deleted_at</code> is null order by <code>stars</code> desc)</p>
  </blockquote>
  
  <p>I understand this, stars doesn't exist in database, but how I can make this working?</p>