Analyzing your code
You have already sorted the created_at
column using the latest()
function. If you want to sort within this by views, it can only consider the order of views where the created_at
values are the same.
latest()
- Laravel Docs
Original Records
I'll show you an example:
posts table
------------------------------------------
ID | name | viewer | created_at
------------------------------------------
1 | First | 12 | 2022-01-01
2 | Secon | 8 | 2022-01-02
3 | Examp | 46 | 2022-01-01
4 | Usual | 21 | 2022-01-03
5 | Nowus | 32 | 2022-01-01
$query = Post()::latest(); // order by created_at desc
Result after order by created_at
desc
Now value of $query
:
posts table
------------------------------------------
ID | name | viewer | created_at
------------------------------------------
4 | Usual | 21 | 2022-01-03
2 | Secon | 8 | 2022-01-02
1 | First | 12 | 2022-01-01
3 | Examp | 46 | 2022-01-01
5 | Nowus | 32 | 2022-01-01
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:
$query = Post()::latest(); // order by created_at desc
$query->orderByDesc('viewer'); // then... order by viewer desc
Result after order by created_at
desc AND order by viewer
desc
Now value of $query
:
posts table
------------------------------------------
ID | name | viewer | created_at
------------------------------------------
4 | Usual | 21 | 2022-01-03
2 | Secon | 8 | 2022-01-02
3 | Examp | 46 | 2022-01-01 <---
5 | Nowus | 32 | 2022-01-01
1 | First | 12 | 2022-01-01 <--- order by viewer where has same date
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 function latest()
. Instead, you can directly sort by the viewer
column.
Original Records
I'll show you an example:
posts table
------------------------------------------
ID | name | viewer | created_at
------------------------------------------
1 | First | 12 | 2022-01-01
2 | Secon | 8 | 2022-01-02
3 | Examp | 46 | 2022-01-01
4 | Usual | 21 | 2022-01-03
5 | Nowus | 32 | 2022-01-01
if ($request->input('popular') == 'true') {
// if need return with order by viewer (so, value of created_at doesn't matter)
$query = Post::orderByDesc('viewer');
}
else {
// else, need return with order by created at date
$query = Post::latest();
}
return $query;
Result after order by viewer
desc [IF $request->input('popular') WILL TRUE]
I'll show you an example:
posts table
------------------------------------------
ID | name | viewer | created_at
------------------------------------------
3 | Examp | 46 | 2022-01-01
5 | Nowus | 32 | 2022-01-01
4 | Usual | 21 | 2022-01-03
1 | First | 12 | 2022-01-01
2 | Secon | 8 | 2022-01-02