php - Is there a way to orderBy orOrderBy in laravel (8)?

I have a scoped method on a laravel model:
public function scopeSort($query, array $params = []) {
return $query->orderBy('read');
}
What I would like to do is say: if there are no items with read = true, then orderByDesc on id.
For example:
public function scopeSort($query, array $params = []) {
return $query->orderBy('read')->orOrderByDesc('id');
// Find all with a read of true or, if there is none, order the collection by id in descending order.
}
Does anything like this exist? Or is there some other way I can achieve this?
Answer
Solution:
You can chain your sorts :
public function scopeSort($query, array $params = []) {
return $query->orderBy('read')->orderBy('id','desc');
}
Example with :
ID read
1 0
4 0
3 0
You'll get :
ID read
4 0
3 0
1 0
Example with :
ID read
1 0
4 1
3 1
5 0
6 1
You'll get :
ID read
5 0
1 0
6 1
4 1
3 1
In the case where all read = 0, the query will sort by ID desc. In the case where there are some read = 1, the query will sort by read, then ID.
EDIT: to be precise, the query will always sort by 'read' then 'ID', but I guess you'll have what you want
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to undefined function mysqli_connect()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.