I’m using query and orderby isn’t working
$query = Post::query()->latest();
if ($request->input('popular') == 'true') {
$query->where('hide_search',0)->orderByDesc('viewer');
}
and
if ($request->input('popular') == 'true') {
$query->where('hide_search',0)->orderByDesc('posts.viewer');
}
and
if ($request->input('popular') == 'true') {
$query->where('hide_search',0)->orderBy('posts.viewer','DESC');
}
2
Answers
First the
latest()
method already applies a "order by" keyword to your query, and takes the priority. Secondly, I’m confused as to what you’re trying to do, as all your if statements have the same condition. And finally, if you want to add additional clauses to your keywords inside conditional statements, you should also update your original query variable, like this:Analyzing your code
You have already sorted the
created_at
column using thelatest()
function. If you want to sort within this by views, it can only consider the order of views where thecreated_at
values are the same.latest()
– Laravel DocsOriginal Records
I’ll show you an example:
Result after order by
created_at
descNow value of
$query
:If you perform another sorting after this, you won’t be able to override the sorting applied to the
created_at
column. Instead, you can only establish a more specific order within the records that have the same date:Result after order by
created_at
desc AND order byviewer
descNow value of
$query
:Solution for get popular post
If you need the most popular post, you don’t need to sort by the
created_at
column using the fast functionlatest()
. Instead, you can directly sort by theviewer
column.Original Records
I’ll show you an example:
Result after order by
viewer
desc [IF $request->input(‘popular’) WILL TRUE]I’ll show you an example: