I have an app where users can favorite venues, this is done via a many to many relationship with a “favorites” pivot table.
Now I want to retrieve the top 10 most times favorited Venues with Eloquent.
My models:
//User model public function favorites() { return $this->belongsToMany('AppModelsVenue', 'favorites', 'user_id', 'venue_id')->withTimeStamps(); } //Venue model public function favorites() { return $this->belongsToMany('AppModelsUser', 'favorites', 'venue_id', 'user_id')->withTimeStamps(); }
Thanks in advance!
Advertisement
Answer
Maybe try this :
$venues = Venue::withCount('favorites')->orderByDesc('favorites_count')->take(10)->get();