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.
Project::orderBy('created_at', 'DESC')
– stalatest('created_at')->take(5)
. – Makdous