I want to sort/order a query in laravel. For example I have a model where ‘id’ ranges from 1 to 100. And I have an array of ids of selected model elements eg. [1,3,12,32,…].
I want to sort my model based on its id being present in the array. For ascending order the elements not present in the array will come first and for descending order the element present in the array will come first.
I have tried to use callback function in orderBy() clause but it doesn’t work.
2
Answers
You can directly order by
IN
in your queryA safer way would be
In Laravel, if you want to sort a query based on whether an ID is present in a given array, you can achieve this using a combination of orderByRaw and conditional sorting. Here’s how you can accomplish sorting based on whether an ID is present in an array:
Scenario
You have a model with id values ranging from 1 to 100, and an array of selected IDs (e.g., [1, 3, 12, 32, …]). You want to sort your results such that:
Solution
To accomplish this, you need to use a CASE statement within orderByRaw to prioritize records based on whether their IDs are in the array.
Here’s how you can do it:
example, let’s assume it’s stored in a variable $selectedIds.
based on the presence of IDs in the array.
Example Code
This approach should give you the flexibility to sort based on the presence of IDs in your array and order the results according to your needs.