Sort items from a Collection from a predefined value
I have a Collection
from Eloquent and would like to sort it by two fields at once being one of them a predefined value.
Ex.: this Collection
has several objects of type Categoria
and I want to sort it so that the categories that have the property slug
equal to "solicitacoes"
are at the beginning and I want the others to be in alphabetical order.
I know that the sort
method can receive a callback to sort the collection and I tried to do (among others things) this
$sorted = $categorias->sort(function ($item, $next) {
return $item->slug === 'solicitacoes' ? -1 :
strcmp($item->descricao, $next->descricao);
});
But the ordering did not work out very well, disregarding the categories with slug = "solicitacoes"
was in alphabetical order, the problem is that the aforementioned were not at the beginning.
2 answers
Using Collection
, I replace the sort
method with SortBy
.
The sortBy
method internally causes Laravel to compare the values according to the types, through the sort
(something similar to what you did in the question using the sort
).
Thus, we can check in sortBy
if the value of slug
is equivalent to "solicitações"
. If so, we return NULL
so that this item is placed above. Otherwise, we return "descricao"
to sort by this field.
See:
$sorted = $categorias->sortBy(function ($item)
{
return $item->slug === 'solicitacoes' ? null : $item->descricao;
});
With the method sort
and your rule has no how, what should be done is a where
and then a union
excluding:
$sort = $categorias->where('slug', 'solicitacoes')
->sortBy('descricao')
->union($categorias->where('slug','<>', 'solicitacoes')->sortBy('descricao'))
->all();
References: