230

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?

Josh
  • 5,089
  • 6
  • 26
  • 43

3 Answers3

416

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

$posts = Post::orderBy('id', 'DESC')->get();
Chris G
  • 5,480
  • 2
  • 15
  • 20
63

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

George Garchagudashvili
  • 6,657
  • 12
  • 39
  • 53
Relaxing In Cyprus
  • 1,838
  • 19
  • 24
  • where is the query being passed to `idDescending()` in the last line `$posts = Post::idDescending()->get();` – Alexander Solonik Feb 20 '15 at 13:59
  • 3
    Laravel parses that automatically. – Relaxing In Cyprus Feb 21 '15 at 22:18
  • 1
    I would go with this answer. Here's how I do it normally on my everyday work: Within the mode: ```public function scopeLatest($query) { return $query->orderBy('created_at')->get(); }``` And within the controller: ```return view('project.view')->with(['projects' => Project::latest()]);``` – Md Mazedul Islam Khan Feb 23 '16 at 09:59
  • I like this answer the best vs handling in-line, esp if you are handling multiple order conditions. Thanks! `_.orderBy(this.users, ['name', 'last_login'], ['asc', 'desc'])` – kaleazy Mar 22 '19 at 20:37
32

This is how I would go about it.

$posts = $this->post->orderBy('id', 'DESC')->get();
Matthew Camp
  • 786
  • 4
  • 9