title: Laravel default orderBy
body: <p>Is there a clean way to enable certain models to be ordered by a property by <strong>default</strong>?
  It could work by extending the laravel's QueryBuilder, but to do so, you'll have to rewire some of it's core features - bad practice.</p>
  
  <p><strong>reason</strong></p>
  
  <p>The main point of doing this is - one of my models get's heavily reused by many others and right now you have to resort the order over and over again. Even when using a closure for this - you still have to call it. It would be much better to be able to apply a default sorting, so everyone who uses this model, and does not provide custom sorting options, will receive records sorted by the default option. Using a repository is not an option here, because it get's eager loaded.</p>
  
  <p><strong>SOLUTION</strong></p>
  
  <p>Extending the base model:</p>
  
  <pre><code>protected $orderBy;
  protected $orderDirection = 'ASC';
  
  public function scopeOrdered($query)
  {
      if ($this-&gt;orderBy)
      {
          return $query-&gt;orderBy($this-&gt;orderBy, $this-&gt;orderDirection);
      }
  
      return $query;
  }
  
  public function scopeGetOrdered($query)
  {
      return $this-&gt;scopeOrdered($query)-&gt;get();
  }
  </code></pre>
  
  <p>In your model:</p>
  
  <pre><code>protected $orderBy = 'property';
  protected $orderDirection = 'DESC';
  
  // ordering eager loaded relation
  public function anotherModel()
  {
      return $this-&gt;belongsToMany('SomeModel', 'some_table')-&gt;ordered();
  }
  </code></pre>
  
  <p>In your controller:</p>
  
  <pre><code>MyModel::with('anotherModel')-&gt;getOrdered();
  // or
  MyModel::with('anotherModel')-&gt;ordered()-&gt;first();
  </code></pre>