ChatGPT解决这个技术问题 Extra ChatGPT

Laravel 4: how to "order by" using Eloquent ORM [duplicate]

This question already has answers here: Laravel Eloquent: Ordering results of all() (12 answers) Closed 6 years ago.

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?

Couldn't you do something like: $posts = $this->post->orderBy('id', 'DESC')->get();
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.
Thanks for asking. Was exactly what I was looking for.
in laravel 5 you can use: ->orderByDesc('id');

C
Chris G

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

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

Still works in 5.1
Absolutely still working in 5.4
working fine in 5.5 also
i'll save the next guy from having to post in the future, works in 5.7 too
😳😳😳 also working in laravel 28.6 in 2036... I just arrived from future and saw this question...
G
George G

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


where is the query being passed to idDescending() in the last line $posts = Post::idDescending()->get();
Laravel parses that automatically.
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()]);
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'])
M
Matthew Camp

This is how I would go about it.

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