3
votes

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.

1
It should be Project::orderBy('created_at', 'DESC')sta
Or latest('created_at')->take(5).Makdous

1 Answers

4
votes

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();