Reputation: 503
This is my index action from my TagsController:
if(Input::get('filter') == 'most-used')
{
$tags = Tag::with('questions')->orderBy('name', 'asc')->paginate(10);
return View::make('tags.index', compact('tags'));
}
I would like the tags with the most questions first.
How do you do that?
Thanks in advance!
Upvotes: 0
Views: 336
Reputation: 3461
Here is how I did it :
if(Input::get('filter') == 'most-used')
{
$tags = Tag::select(
'*',
DB::raw("(SELECT COUNT(*) FROM `questions_tags` WHERE `tag_id` = `tags`.`id`) AS 'count'")
)
->orderBy('count', 'desc')
->paginate(10);
return View::make('tags.index', compact('tags'));
}
Upvotes: 1
Reputation: 752
Try this:(untested)
$tags = Tag::with('questions')->orderBy('name', 'asc')->paginate(10);
$tags = $tags->sortBy(function($tag){
return $tag->questions->count();
});
return View::make('tags.index', compact('tags'));
Upvotes: 0