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?
If you are using post as a model (without dependency injection), you can also do:
$posts = Post::orderBy('id', 'DESC')->get();
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
idDescending()
in the last line $posts = Post::idDescending()->get();
public function scopeLatest($query) { return $query->orderBy('created_at')->get(); }
And within the controller: return view('project.view')->with(['projects' => Project::latest()]);
_.orderBy(this.users, ['name', 'last_login'], ['asc', 'desc'])
This is how I would go about it.
$posts = $this->post->orderBy('id', 'DESC')->get();
Success story sharing