Laravel 4: how to "order by" using Eloquent ORM

PhpLaravelLaravel 4Eloquent

Php Problem Overview


Simple question - how do I order by 'id' descending in Laravel 4.

The relevant part of my controller looks like this:

$posts = $this->post->all()

As I understand you use this line:

->orderBy('id', 'DESC');

But how does that fit in with my above code?

Php Solutions


Solution 1 - Php

If you are using post as a model (without dependency injection), you can also do:

$posts = Post::orderBy('id', 'DESC')->get();

Solution 2 - Php

If you are using the Eloquent ORM you should consider using scopes. This would keep your logic in the model where it belongs.

So, in the model you would have:

public function scopeIdDescending($query)
{
        return $query->orderBy('id','DESC');
}   

And outside the model you would have:

$posts = Post::idDescending()->get();

More info: http://laravel.com/docs/eloquent#query-scopes

Solution 3 - Php

This is how I would go about it.

$posts = $this->post->orderBy('id', 'DESC')->get();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoshView Question on Stackoverflow
Solution 1 - PhpChris GView Answer on Stackoverflow
Solution 2 - PhpRelaxing In CyprusView Answer on Stackoverflow
Solution 3 - PhpMatthew CampView Answer on Stackoverflow