269

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,999
  • 8
  • 30
  • 43
  • 9
    Couldn't you do something like: $posts = $this->post->orderBy('id', 'DESC')->get(); – Matthew Camp Jul 09 '13 at 16:20
  • Yep, sorry I was having trouble with the syntax. Thanks - If you post that as an answer I will happily selected it as the correct answer. – Josh Jul 09 '13 at 16:23
  • in laravel 5 you can use: ->orderByDesc('id'); –  Mar 13 '18 at 10:50

3 Answers3

510

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

$posts = Post::orderBy('id', 'DESC')->get();
Chris G
  • 6,700
  • 2
  • 18
  • 20
74

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 G
  • 7,443
  • 12
  • 45
  • 59
Relaxing In Cyprus
  • 1,976
  • 19
  • 25
  • 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
39

This is how I would go about it.

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