Reputation: 1828
I'm trying to get a list of 5 recent projects and sort them in descending order based on the created_at date field. I'm using Model::with() to avoid the n+1 problem. Below is the code:
$recentProjects = Project::with('visits','team')
->whereYear('created_at',now()->year)
->sortByDesc('created_at')->take(5)
->get();
However, I get the error:
Call to undefined method Illuminate\Database\Eloquent\Builder::sortByDesc()
I tried different ways, like Project::orderBy()
followed by with, and didn't workout either.
Upvotes: 7
Views: 12062
Reputation: 34708
The sortByDesc
method sorts the collection by field that belongs to some eloquent relation in your model.
If you are trying to sort collection with sortByDesc
for model itself ( your current object of model), use orderBy
rather than sortByDesc
:
Project::orderBy('created_at', 'DESC')
->with('visits','team')
->whereYear('created_at', now()->year)
->take(5)
->get();
Upvotes: 11