2

I see you can call my MyModel::all() and then call "where" "groupBy" .. etc I cant seem to find orderBy as this Q & A suggest.. Has this been removed in Laravel 5?

I've tried looking through the docs for a reference in Collection and Model but I'm assuming these are actually just modifiers for the collection returned and not actually modifying the query statement..

The only way I know of using order by is

\DB::table($table)->where($column)->orderBy($column);

Is that the only way to order your database select when executing a query?

Community
  • 1
  • 1
StrikeForceZero
  • 2,379
  • 1
  • 25
  • 36

3 Answers3

5

You can actually just use it like where and groupBy:

$result = MyModel::orderBy('name', 'desc')->get();

Note that by calling MyModel::all() you're already executing the query.


In general you can pretty much use every method from the query builder documented here with Eloquent models. The reason for this is that the model proxies method calls (that it doesn't know) to a query builder instance:

public function __call($method, $parameters)
{
    // irrelevant code omitted

    $query = $this->newQuery();

    return call_user_func_array(array($query, $method), $parameters);
}

$this->newQuery() creates an instance of the query builder which then is used to actually run the query. Then when the result is retrieved the model/collection is hydrated with the values from the database.


More info

Eloquent - Laravel 5 Docs

Illuminate\Database\Eloquent\Builder - API docs

And also the regular query builder (since quite a few calls get passed from the eloquent builder) Illuminate\Database\Query\Builder - API docs

lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • Interesting... I was expecting it to not work since there was no code hinting suggesting it in my IDE (Netbeans with laravel ide helper). Do these calls have any documentation? I must be blind – StrikeForceZero Mar 05 '15 at 19:35
  • 2
    @DesignerGuy Thanks. Not to forget the actual query builder because many calls just get passed from the eloquent builder... – lukasgeiter Mar 05 '15 at 19:48
  • 1
    @StrikeForceZero For better IDE coverage when using Laravel, use this: https://github.com/barryvdh/laravel-ide-helper – rmobis Aug 02 '15 at 00:39
0

You can achieve this with the following solution:

$result = ModelName::orderBy('id', 'desc')->get();
Martin Reiche
  • 1,642
  • 1
  • 16
  • 27
0

You can do it by using sort keys

Model::all()->sortKeys()

(or)

Model::all()->sortKeysDesc()